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,5
Code language: plaintext (plaintext)
The List<T> class stores data in a dynamically sized array. So converting an array to a list boils down to copying the array to the list’s internal array. That’s what ToList() does. It creates a new list with the List<T>(array) constructor. This constructor copies the array to the list’s internal array (with Array.Copy()). You can call this constructor yourself if you don’t want to use ToList(). I’ll show that next.
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,5
Code 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,6
Code 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).