C# – Convert an array to a list

The simplest way to convert an array to a list is with the ToList() Linq method:

using System.Linq;

var array = new int[]
{
    1,2,3,4,5
};

var list = array.ToList();

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

This outputs the following:

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

Besides using ToList(), you can also use the list constructor or AddRange(). Before I show those, I’ll explain why you’d want to use these special methods instead of just adding items individually to a new list.

Don’t add items to the list individually

You may be wondering, why not just loop through the array and add items to a list one at a time? Simply put, a List in .NET has an internal array, which stores data in a contiguous block in memory. Because of this, you can copy chunks of memory from one array to another, which is way more efficient than copying individual items one at a time. That’s what ToList() does behind the scenes, it uses Array.Copy() to efficiently copy data from an array to its internal array.

Use the List<T>(array) constructor

You can convert an array to a list by using the List<T>(array) constructor:

var array = new int[]
{
    1,2,3,4,5
};

var list = new List<int>(array);

Console.WriteLine(string.Join(",", list)); //outputs 1,2,3,4,5
Code language: C# (cs)

This outputs the following:

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

Copy array to an existing list with List.AddRange()

If the list already exists, you can use List.AddRange() to copy the array to the end of the list:

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

var array = new int[]
{
    4,5,6
};

list.AddRange(array);

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

This outputs the following (notice how the array’s elements 4,5,6 are appended to end of the list):

1,2,3,4,5,6Code language: plaintext (plaintext)

Internally, List.AddRange() uses Array.Copy() to copy the array to the end of the list’s internal array (resizing it if necessary).

Leave a Comment