tags:

views:

260

answers:

2

Last night I had dream that the following was impossible. But in the same dream, someone from SO told me otherwise. Hence I would like to know if it it possible to convert System.Array to List

    Array ints = Array.CreateInstance(typeof(int), 5);
    ints.SetValue(10, 0);
    ints.SetValue(20, 1);
    ints.SetValue(10, 2);
    ints.SetValue(34, 3);
    ints.SetValue(113, 4);

to

List<int> lst = ints.OfType<int>(); ( not working)
+7  A: 

Save yourself some pain...

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

List<int> lst = ints.OfType<int>().ToList();

Can also just...

List<int> lst = new List<int> { 10, 20, 10, 34, 113 };
Dave
Oops almost i was near....... :)
Note for completeness: the 2nd method is only available in C# 3.0+.
Jon Seigel
+3  A: 

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);
Matthew Whited
Thanks for another approcah