The List<T>
class in the System.Collections.Generic
namespace provides the ToArray()
method, which can be used to convert a C# List to an Array.
public T[] ToArray();
This method copies the items of the List
This method uses the Array.Copy()
method internally to copy the list elements to a new array.
Since it copies all the elements, the time complexity of this method is O(n)
, where n
is the number of elements.
In the code example below, we create a list of integers and convert it to an array of integers using the ToArray()
method. We have printed the Array contents using the Array.ForEach()
method.
The same operation is demonstrated for a list of strings as well.
The program prints the output below.
1
2
3
4
5
January
February
March
April
using System;using System.Collections.Generic;namespace Hello{class ToArrayTest{static void Main(string[] args){var numList = new List<int> { 1, 2, 3, 4, 5 };int[] numArray = numList.ToArray();Array.ForEach(numArray, Console.WriteLine);var monthList = new List<string> { "January", "February", "March", "April" };string[] monthArray = monthList.ToArray();Array.ForEach(monthArray, Console.WriteLine);}}}