94

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;
}

8 Answers 8

180

Try using

MyClass[] myArray = list.ToArray();
1
  • That makes a shallow copy, correct? Is unclear from the docs...
    – rustyx
    Commented Jun 2, 2021 at 11:03
21
List<int> list = new List<int>();
int[] intList = list.ToArray();

is it your solution?

10
list.ToArray()

Will do the tric. See here for details.

9

Use ToArray() on List<T>.

0

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();

According to Docs

The elements are copied using Array.Copy(), which is an O(n) operation, where n is Count.

0

To go twice as fast by using multiple processor cores HPCsharp nuget package provides:

list.ToArrayPar();
0

One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:

list.AsParallel().ToArray();
0

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]

Not the answer you're looking for? Browse other questions tagged or ask your own question.