Reputation: 10369
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;
}
Upvotes: 95
Views: 186674
Reputation: 319
With the release of C# 12 in .Net 8 (Visual Studio 2022 17.8+), the spread operator (similar to JavaScript) can be used in a collection expression to make a shallow copy of the elements of one collection into another. See more here.
MyClass[] myArray = [.. list];
For the purposes of converting a list to an array, this is semantically equivalent to list.ToArray()
. However, this syntax can be used with any group of collection types.
int[] array = [1, 2, 3];
Span<int> span = [4, 5, 6];
List<int> list = [7, 8, 9];
List<int> combined = [.. array, .. span, .. list]; // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 1
Reputation: 470
One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:
list.AsParallel().ToArray();
Upvotes: 0
Reputation: 470
To go twice as fast by using multiple processor cores HPCsharp nuget package provides:
list.ToArrayPar();
Upvotes: 0
Reputation: 7006
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.
Upvotes: 0
Reputation: 1099
List<int> list = new List<int>();
int[] intList = list.ToArray();
is it your solution?
Upvotes: 22