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
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5