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
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).
Success story sharing
Aggregate
is better for Math type operations. With strings this operation it is similar tofor 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.StringBuilder.AppendJoin()
looks like exactly what the op need:var names = new List<string>() { "John", "Anna", "Monica" }; string joinedNames = new StringBuilder().AppendJoin(", ", names);
It's roughly same asstring.Join()
, I've not preformance-tested this. In case you desperately need a Linq form, without aggregation:var names = new List<string>() { "John", "Anna", "Monica" }; var joinedNames = new System.Text.StringBuilder(); names.ForEach(a => joinedNames.Append((joinedNames.Length > 0 ?", " : "") + a)); //joinedNames.ToString();