This post will discuss how to convert a list to a string in C# where individual elements of the list are joined into a single string using a given delimiter. The delimiter should not be added before or after the list.
1. Using String.Join()
method
The recommended solution is to use the String.Join() method of the string class, which joins elements of the specified array or collection together with the specified delimiter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string>() { "A", "B", "C" }; char delim = ','; string str = String.Join(delim, list); Console.WriteLine(str); } } /* Output: A,B,C */ |
2. Using Enumerable.Aggregate()
method
Like the above method, LINQ provides the Aggregate() method, which can join elements of a list using a delimiter. The following code example shows how to implement this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<string> list = new List<string>() { "A", "B", "C" }; char delim = ','; string str = list.Aggregate((x, y) => x + delim + y); Console.WriteLine(str); } } /* Output: A,B,C */ |
3. Using StringBuilder
A naive solution is to loop through the list and concatenate each list element to the StringBuilder
instance with the specified delimiter. Finally, we return the string representation of the StringBuilder
. Note that the solution handles trailing delimiters’ characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Collections.Generic; using System.Text; public class Example { public static void Main() { List<string> list = new List<string>() { "A", "B", "C" }; char delim = ','; StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { sb.Append(list[i]); if (i < list.Count - 1) { sb.Append(delim); } } string str = sb.ToString(); Console.WriteLine(str); } } /* Output: A,B,C */ |
That’s all about converting a List to a String using a delimiter in C#.