This article will explain, How to convert the List to the Array using the C# code. Here I’m explaining three ways to do it. Let’s go through them, one by one.
Using ToArray() Method
This method converts the List to Array very easily. It returns the Array containing the elements, copied from the list. Check the below code.
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)); } }
Using Enumerable.Select() Method
This method is used to convert a list of one type to another type of Array. Check the below code.
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)); } }
Here, I’m converting the string type of a list to the int type of an Array.
Using ConvertAll() Method
If you don’t want to use LINQ to convert one type of a List to another type of Array. Then you can use this method.
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)); } }