Thursday 3 February 2011

CSharp: Get a List from an array

Question:
I have an array and need a list.
How do I transform the array into a list of objects?



Answer:
You do not transform the array into a list.
You initialize the list with the array content.

Here is an example
// Array of strings with 4 elements
    string[] parts = new string[4] {"My", "Name", "is", "John"}; 
    // Initialize a List with the array
    List<string> list = new List<string>(parts);
    // 4 elements in List
    Console.WriteLine(list.Count); 
   ...

Answer 2:
You can also use Linq.
If you import the System.Linq namespace you can use the extension method on IEnumberable<T>.

Here is an example
// Array of strings with 4 elements
    using System.Linq;
    ...
    string[] parts = new string[4] {"My", "Name", "is", "John"}; 
    // Initialize a List with the array
    List<string> list = parts.ToList();
    // 4 elements in List
    Console.WriteLine(list.Count); 
   ...

No comments: