Conversion from List<T> to array T[]

C#.NetArraysLinqList

C# Problem Overview


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

C# Solutions


Solution 1 - C#

Try using

MyClass[] myArray = list.ToArray();

Solution 2 - C#

List<int> list = new List<int>();
int[] intList = list.ToArray();

is it your solution?

Solution 3 - C#

Use ToArray() on List<T>.

Solution 4 - C#

list.ToArray()

Will do the tric. See here for details.

Solution 5 - C#

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.

Solution 6 - C#

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

list.AsParallel().ToArray();

Solution 7 - C#

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

list.ToArrayPar();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontehvanView Question on Stackoverflow
Solution 1 - C#Nikos SteiakakisView Answer on Stackoverflow
Solution 2 - C#Sessiz SaatView Answer on Stackoverflow
Solution 3 - C#Brian RasmussenView Answer on Stackoverflow
Solution 4 - C#Bas BossinkView Answer on Stackoverflow
Solution 5 - C#NipunaView Answer on Stackoverflow
Solution 6 - C#DragonSpitView Answer on Stackoverflow
Solution 7 - C#DragonSpitView Answer on Stackoverflow