Convert List of Int to Array of Int in C#
This post will discuss how to convert List of Int to Array of Int in C#.
1. Using List<T>.ToArray() Method
The standard solution to convert a List<T> into a T[] is to invoke the List<T>.ToArray() method on the List. It copies all elements of a List<T> to a new array of the same type. The following example demonstrates the usage of the ToArray() method to create an array containing copies of the elements of the List.
|
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>() { 5, 3, -8, 7, -1 }; int[] array = list.ToArray(); Console.WriteLine(String.Join(", ", array)); // 5, 3, -8, 7, -1 } } |
2. Using List<T>.CopyTo() Method
The List<T>.CopyTo() method copies the List<T> (or a portion of it) to an array. You can use it as follows to convert a List of integers to an array of integers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int>() { 5, 3, -8, 7, -1 }; int[] array = new int[list.Count]; list.CopyTo(array); Console.WriteLine(String.Join(", ", array)); // 5, 3, -8, 7, -1 } } |
That’s all about converting List of Int to Array of Int 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 :)