C# Convert-List To Array

C# Convert-List To Array

  Here is trick to convert the list into an array.
Example shows a method of list instance as ToArray(). Isn't
it that simple to get array from list collection.

We have used list of strings, you may use your custom class list to get an array of your custom class instances.

Example


using System;
using System.Collections.Generic;
using System.Text;

using System.Collections.Generic;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> lstString = new List<string>();

            lstString.Add("FaceBook");
            lstString.Add("Yahoo");
            lstString.Add("Hotmail");
            lstString.Add("Password");
            lstString.Add("Bing");
            lstString.Add("Google");

            string[] arrString = lstString.ToArray();

            foreach (string s in arrString)
            {
                Console.WriteLine(s);           
            }

            Console.ReadKey();


        }
    }
}


output

FaceBook
Yahoo
Hotmail
Password
Bing
Google

Description:

List is generic which can hold any data type including string or your custom class, System.Collections.Generic
namespace is used for defining list.
In above code the instance method ToArray() returns array of list elements

lstString.ToArray();

The foreach loop is used to print an elements of array.

To convert array to list follow below link

http://www.revenmerchantservices.com/post/c-convert-array-to-list.aspx

Tags:

Linq Convert String Array To Int ArrayC# Convert-List To ArrayHow To Declare and access array of string in C#One dimensional array example C#.net VB.netC# Char ArrayC# foreach loopC# looping through arrayC# Arraylist foreachC# ArrayList Search using Linq Extension OfType MethodC# convert array to listConvert Array To Comma Separated String C#

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.