Convert List of string to Array of string in C#
This post will discuss how to convert a List of strings to an array of strings in C#.
The standard solution to convert a list of any type to an array of the “same” type is using the ToArray() method. The following code example creates an array of four elements by invoking the ToArray() method on a List.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string> { "1", "2", "3", "4" }; string[] array = list.ToArray(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4 } } |
Alternatively, to transform a list of any type to an array of “another” type, you can use the Select() method by LINQ. The following code example demonstrates how to use the Select() method to project over a list of integer values, and convert each integer to a string before invoking the ToArray() method to get an array of strings.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 2, 3, 4 }; string[] array = list.Select(x => x.ToString()).ToArray(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4 } } |
A better non-LINQ solution is to use the List<T>.ConvertAll() method for converting a list of one type to other types. We can use it as follows to convert a List of strings to an array of strings.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 2, 3, 4 }; string[] array = list.ConvertAll(x => x.ToString()).ToArray(); Console.WriteLine(String.Join(", ", array)); // 1, 2, 3, 4 } } |
That’s all about converting a List of strings to an array of strings in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)