How to Convert list to array in C#
By FoxLearn 3/5/2025 3:04:31 AM 21
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.
- How to Parser a CSV file in C#
- How to read configuration from appsettings.json in C#
- How to Programmatically Update appsettings.json in C#
- How to deconstruct an object in C#
- Handling CSV Files Without a Header Row Using CsvHelper
- CSVHelper: Header with name not found
- How to Convert a Comma-Separated String into a List of Integers in C#
- How to send synchronous requests with HttpClient in C#