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
Comments (0)