Convert a List of strings to a comma-separated string in C#
This article illustrates the different techniques to convert a List<string> to a comma-separated string in C#.
1. Using String.Join() method
The standard solution to convert a List<string> to a comma-separated string in C# is using the string.Join() method. It concatenates members of the specified collection using the specified delimiter between each item.
|
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> strings = new List<string> { "a", "b", "c" }; string concat = string.Join(",", strings); Console.WriteLine(concat); // a,b,c } } |
2. Using Enumerable.Aggregate() method
Alternatively, you can use the LINQ Aggregate() method, which applies an accumulator function on each item of the calling sequence. This can be used as follows to concatenate each member of the list. Note that you need to add the System.Linq namespace.
|
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<string> strings = new List<string> { "a", "b", "c" }; string concat = strings.Aggregate((x, y) => x + "," + y); Console.WriteLine(concat); // a,b,c } } |
That’s all about converting a List<string> to a comma-separated string 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 :)