How to Convert an array to a list in C#
By FoxLearn 3/5/2025 2:59:35 AM 58
using System.Linq; var array = new int[] { 1, 2, 3, 4, 5 }; var list = array.ToList(); Console.WriteLine(string.Join(",", list));
This outputs the following:
1,2,3,4,5
Besides using ToList()
, there are a couple of other methods to convert an array into a list: the List<T>
constructor and List.AddRange()
. Before diving into those methods, it’s worth explaining why using these special methods is more efficient than adding individual items one by one.
You might wonder why not just loop through the array and add items to a list one at a time. The reason is that a List<T>
in .NET uses an internal array to store data contiguously in memory. This means copying chunks of memory from one array to another is far more efficient than copying each element individually. That’s exactly what ToList()
does behind the scenes it uses Array.Copy()
to perform this memory copy efficiently.
Using the List<T>(array) Constructor
You can also 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
This outputs the following:
1,2,3,4,5
Copy Array to an Existing List with List.AddRange()
If you already have a list and want to copy an array into it, you can use List.AddRange()
to append 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));
This outputs:
1,2,3,4,5,6
As you can see, the array’s elements 4, 5, 6
are appended to the end of the existing list.
Internally, List.AddRange()
uses Array.Copy()
to efficiently copy the array into the list’s internal array, resizing it as necessary.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#