Transform collection to comma separated list

Today I had to transform a collection of integers into a string in the form of a comma separated list. In the old-style- approach it would probably be something like:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
StringBuilder strb = new StringBuilder();
foreach (int number in numbers)
{
strb.Append(number.ToString());
strb.Append(",");
}
string commeSeparatedList = strb.ToString().TrimEnd(',');

But actually this can be done in a short way, like:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
string commaSeparatedList = string.Join(",",
numbers.Select(n => n.ToString()).ToArray());

which produces the same result. In my case it was not a collection of integers, but a list of objects; but it’s the same approach:
 
string commaSeparatedListOfGroups = string.Join(",", 
allRelatedGroups.Select(g => g.Id.ToString()).ToArray());

 

Leave a comment