C# – Convert list to array

The simplest way to convert a list to an array is to use the List.ToArray() method:

var list = new List<int>()
{
    1,1,2,3,5,8
};

var array = list.ToArray();

Console.WriteLine(string.Join(",", array));
Code language: C# (cs)

This outputs the following:

1,1,2,3,5,8Code language: plaintext (plaintext)

Internally, the List<T> class stores elements in a dynamically sized array (it resizes when necessary). So under the hood, List.ToArray() uses Array.Copy() to copy the list’s internal array to a new array. This is very efficient.

Copy list to existing array

If you already have an array, you can copy elements from the list to the array with List.CopyTo(). Internally, this uses Array.Copy() to copy the list’s internal array to the destination array.

Here’s an example of copying all elements from a list to an existing array:

var list = new List<int>()
{
    1,2,3
};

var array = new int[3];

list.CopyTo(array);

Console.WriteLine(string.Join(",", array));
Code language: C# (cs)

This outputs the following:

1,2,3Code language: plaintext (plaintext)

You can also use List.CopyTo() to copy some of the elements (instead of all of them) to a specific part of the array. You do this by specifying the starting index (and optionally the count) to copy to. Here’s an example:

var list = new List<int>()
{
    1,2,3
};

var array = new int[6];

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

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

Console.WriteLine(string.Join(",", array));
Code language: C# (cs)

After copying, this converts the list to a string and outputs the following:

1,2,3,1,2,3Code language: plaintext (plaintext)

Convert IEnumerable to array

When you use a Linq method such as Select()/Where() on a list, it returns an IEnumerable. The simplest way to convert this IEnumerable to an array is to use the Linq ToArray() method. Here’s an example:

using System.Linq;

var list = new List<int>()
{
    1,2,3,4,5
};

var array = list.Where(n => n < 4).ToArray();

Console.WriteLine(string.Join(",", array));
Code language: C# (cs)

This outputs the following:

1,2,3Code language: plaintext (plaintext)

Note: You may be interested in reading how you’d convert this comma-separated string back to a list of ints.

Leave a Comment