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

 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s