Concatenate all list elements into a string in C#
This post will discuss how to concatenate all list elements into a string in C#.
1. Using String.Join Method
A simple solution to concatenate all the members of a list into a string is using the String.Join method. The member elements are delimited using the specified separator. Note that separator is included in the returned string only if the list contains more than one element.
The following code demonstrates the usage of the String.Join method to concatenate all the items of a list using a comma as a separator.
|
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 str = String.Join(",", strings); Console.WriteLine(str); // A,B,C } } |
2. Using Enumerable.Aggregate Method
Alternatively, you can use the Enumerable.Aggregate() method from LINQ to concatenate all items of a list. It applies an accumulator function over a sequence. Here’s an example of its usage to concatenate list elements using a comma as a delimiter.
|
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 str = strings.Aggregate((i, j) => i + "," + j).ToString(); Console.WriteLine(str); // A,B,C } } |
That’s all about concatenating all list elements into a 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 :)