Sabari M Sabari M
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

Sabari M
Sabari M
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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