C# List<string> to string with delimiter

C#StringListDelimiter

C# Problem Overview


Is there a function in C# to quickly convert some collection to string and separate values with delimiter?

For example:

List<string> names --> string names_together = "John, Anna, Monica"

C# Solutions


Solution 1 - C#

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:

> John, Anna, Monica

Solution 2 - C#

You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnanView Question on Stackoverflow
Solution 1 - C#QuartermeisterView Answer on Stackoverflow
Solution 2 - C#BobView Answer on Stackoverflow