Convert List to Array in C#
This post will discuss how to convert a list to an array in C#.
C# supports straight conversion from a List<T> to an array T[] using the List<T>.ToArray() method. It returns an array containing copies of all the list elements. The following example demonstrates usage of the ToArray() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 2, 3, 4, 5 }; int[] array = list.ToArray(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4, 5 } } |
To convert a list of one type to an array of another type, you can apply a transform function to each list element before invoking the List<T>.ToArray() method. This can be easily done using the Enumerable.Select() method, which projects each element of a sequence into a new form. The following example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string> { "1", "2", "3", "4" }; int[] array = list.Select(int.Parse).ToArray(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4, 5 } } |
If you don’t prefer LINQ, you can use the List<T>.ConvertAll() method to convert a list of one type to a list of another type.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string> { "1", "2", "3", "4" }; int[] array = list.ConvertAll(int.Parse).ToArray(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4 } } |
That’s all about converting a list to an array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)