views:

126

answers:

2

This is my first question so hello to all users!

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 = "John, Anna, Monica"

+15  A: 

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());

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

Quartermeister
In C# 4 you no longer need to change List<string> to an array, IEnumerable<string> is accepted as well.
Simon Steele
And if you're using .NET4 then you don't need the `ToArray` call.
LukeH
+3  A: 

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).

Bob
Thanks for the fast replies, both works fine. You're right I did a small performance measurement using Stopwatch class and the linq-way is much slower: String.Join(", ", names.ToArray()); --> took 18 ticksAggregate((a, b) => a + ", " + b) --> took 736 ticks
Andrzej Nosal
Yeah I think `Aggregate` is better for Math type operations. With strings this operation it is similar to `for each` ing and just appending to a string which is very slow in inefficient because you are creating a new string for each item that exists in the list.
Bob