How to convert a C# list to an Array
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.
Syntax
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), wherenis 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
Code
This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.