[c#] Conversion from List<T> to array T[]

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

This question is related to c# .net arrays linq list

The answer is


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

is it your solution?


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

According to Docs

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


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

list.ToArrayPar();

Use ToArray() on List<T>.


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

list.AsParallel().ToArray();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>