Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
list
array
communitycreator

How to convert a C# list to an Array

Surabhi Sharma

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 to a new array and returns the array to the caller.

  • 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

Code

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);

        }
    }
}

RELATED TAGS

c#
list
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring