Convert an Array to a List in C#
This post will discuss how to convert an array to a list in C#.
1. Using Enumerable.ToList() method
The simplest solution is to call the Enumerable.ToList() method from System.Linq namespace which creates a List<T> from an IEnumerable<T>. It returns a List<T> that contains elements from the input sequence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; List<int> list = array.ToList(); // List<int> list = array.OfType<int>().ToList(); // List<int> list = array.Cast<int>().ToList(); Console.WriteLine(String.Join(",", list)); } } /* Output: 1,2,3,4,5 */ |
2. Using List Constructor
We can also use the constructor of List<T> which accepts IEnumerable<T> as an argument and initializes a new instance of the List<T> class that contains elements copied from the specified collection.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; List<int> list = new List<int>(array); Console.WriteLine(String.Join(",", list)); } } /* Output: 1,2,3,4,5 */ |
3. Using List.AddRange() method
Finally, we can call the AddRange() method, which adds the specified collection elements at the end of the List.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; List<int> list = new List<int>(); list.AddRange(array); Console.WriteLine(String.Join(",", list)); } } /* Output: 1,2,3,4,5 */ |
That’s all about converting an array to a list 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 :)