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"
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>
.
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.
John, Anna, Monica
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).
An extension method based on the accepted answer, that I use in all my projects:
public static string StringJoin(this IEnumerable<string> values, string separator)
{
return string.Join(separator, values);
}
Usage:
var result = names.StringJoin(", ");
P.S. Don't ever use Aggregate
for this, it is two orders of magnitude slower than string.Join