Is there a short way of converting a strongly typed List<T> to an Array of the same type, e.g.: List<MyClass> to MyClass[]?
By short i mean one method call, or at least shorter than:
MyClass[] myArray = new MyClass[list.Count]; int i = 0; foreach (MyClass myClass in list) { myArray[i++] = myClass; } 7 Answers
Try using
MyClass[] myArray = list.ToArray(); 1List<int> list = new List<int>(); int[] intList = list.ToArray(); is it your solution?
Use ToArray() on List<T>.
list.ToArray() Will do the tric. See here for details.
You can simply use ToArray() extension method
Example:
Person p1 = new Person() { Name = "Person 1", Age = 27 }; Person p2 = new Person() { Name = "Person 2", Age = 31 }; List<Person> people = new List<Person> { p1, p2 }; var array = people.ToArray(); The elements are copied using
Array.Copy(), which is an O(n) operation, where n is Count.
One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:
list.AsParallel().ToArray(); To go twice as fast by using multiple processor cores HPCsharp nuget package provides:
list.ToArrayPar();