How to Convert list to array in C#

By FoxLearn 3/5/2025 3:04:31 AM   21
The easiest way to convert a list to an array is by using the List.ToArray() method.

For example:

var list = new List<int> { 10, 20, 30, 40, 50 };
var array = list.ToArray();
Console.WriteLine(string.Join(",", array));

This outputs:

10,20,30,40,50

Internally, the List<T> class uses a dynamically sized array to store its elements, resizing when needed. When you call List.ToArray(), it uses Array.Copy() to copy the list’s internal array into a new array, making it an efficient process.

Copy List to Existing Array

If you already have an existing array and want to copy elements from a list to it, you can use List.CopyTo(). Internally, it uses Array.Copy() to transfer the list’s internal array into the target array.

For example, How to copy all elements from a list into an existing array:

var list = new List<int> { 5, 10, 15 };
var array = new int[3];
list.CopyTo(array);
Console.WriteLine(string.Join(",", array));

This will output:

5,10,15

You can also specify a starting index (and optionally a count) to copy elements to a specific part of the array.

var list = new List<int> { 100, 200, 300 };
var array = new int[6];

// Copies elements starting at index 0
list.CopyTo(array);

// Copies elements starting at index 3
list.CopyTo(array, 3);

Console.WriteLine(string.Join(",", array));

This will output:

100,200,300,100,200,300

Convert IEnumerable to Array

When you apply LINQ methods like Select() or Where() on a list, it returns an IEnumerable. To convert this IEnumerable to an array, you can use the ToArray() method from LINQ.

using System.Linq;

var list = new List<int> { 5, 10, 15, 20, 25 };
var array = list.Where(n => n > 10).ToArray();
Console.WriteLine(string.Join(",", array));

This will output:

15,20,25

Note: If you're curious, you may also want to learn how to convert this array back into a list or handle different data transformations in LINQ.