HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

C# List<string> to string with delimiter

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringwithlistdelimiter

Problem

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

For example:

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

Solution

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

List names = new List() { "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.

In newer versions of .NET different String.Join overloads use different approaches to produce the result. And this might affect the performance of your code.

For example, those that accept IEnumerable use StringBuilder under the hood. And the one that accepts an array uses a heavily optimized implementation with arrays and pointers.
Results:

John, Anna, Monica

Code Snippets

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

Context

Stack Overflow Q#3575029, score: 1762

Revisions (0)

No revisions yet.