Conversion of System.Array to List

There is also a constructor overload for List that will work... But I guess this would required a strong typed array.

//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);

... for Array class

var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
    intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);

Save yourself some pain...

using System.Linq;

int[] ints = new [] { 10, 20, 10, 34, 113 };

List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.

Can also just...

List<int> lst = new List<int> { 10, 20, 10, 34, 113 };

or...

List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);

or...

List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });

or...

var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });

Tags:

C#