TechieClues TechieClues
Updated date Feb 14, 2023
In this blog, we will learn to convert a list of strings to an array in C#

We will use the below methods to convert a list of strings to an array in C#

  • Using ToArray()
  • Using  List<T>.ConvertAll() 

Using ToArray()

The traditional way to convert the list of strings to an array is to use the ToArray() method. It converts the list of strings into an array as shown below,

using System;
using System.Collections.Generic;

namespace ConvertListOfStrToArray
{
    class Program
    {
        static void Main()
        {
            List<string> listOfStr = new List<string> { "Audi", "BMW", "Mazda", "Toyota", "Lexus" };

            string[] array = listOfStr.ToArray();

            Console.WriteLine(String.Join(", ", array));       
            Console.ReadKey();
        }
    }
}

Output:

Audi, BMW, Mazda, Toyota, Lexus

Using  List<T>.ConvertAll()

On the other side, we will use List<T>.ConvertAll() method to convert a list of one type to another. The below example shows how to converting the list of strings to an array,

using System;
using System.Collections.Generic;

namespace ConvertListOfStrToArray
{
    class Program
    {
        static void Main()
        {
            List<string> listOfStr = new List<string> { "Audi", "BMW", "Mazda", "Toyota", "Lexus" };

            string[] array = listOfStr.ConvertAll(x => x.ToString()).ToArray();

            Console.WriteLine(String.Join(", ", array));       
            Console.ReadKey();
        }
    }
}

 Output:

Audi, BMW, Mazda, Toyota, Lexus

 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!