Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of System.Array to List

Tags:

c#

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 
like image 273
user193276 Avatar asked Oct 21 '09 19:10

user193276


People also ask

Can you convert an array to a list C#?

There are multiple ways to convert an array to a list in C#. One method is using List. AddRange method that takes an array as an input and adds all array items to a List. The second method is using ToList method of collection.

Can we convert list into array?

Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.


2 Answers

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 }); 
like image 71
David Avatar answered Oct 11 '22 11:10

David


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); 
like image 27
Matthew Whited Avatar answered Oct 11 '22 10:10

Matthew Whited