Convert a List of strings into a single string in C#
This post will discuss how to convert a list of strings into a single string in C#.
The String.Join convenience method lets you concatenate each element in a list to a single string. It takes a separator to be applied between each element in the returned string. If the list contains a single element, the separator is not included. The following example demonstrates this:
|
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> values = new List<string>() { "C++", "Java", "C#" }; string str = String.Join(", ", values); Console.WriteLine(str); // C++, Java, C# } } |
If the source list is not of type String, the String.Join method will implicitly call that object’s ToString() method on each of the items in the list before concatenating them. For example, the following code concatenates all elements of an integer list using ", " as a delimiter and displays the result as a single string.
|
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> values = new List<int>() { 1, 2, 3 }; string str = String.Join(", ", values); Console.WriteLine(str); // 1, 2, 3 } } |
That’s all about converting a list of strings into a single 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 :)