Ludwig’s Blog

Adventures in .NET

Archive for April, 2010

Transform collection to comma separated list

Posted by Ludwig Stuyck on April 27, 2010

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 commeSeparatedList = 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 is the same approach:

string commaSeparatedListOfGroups = string.Join(",", allRelatedGroups.Select(g => g.Id.ToString()).ToArray());

Posted in Uncategorized | 4 Comments »

Visual Studio 2010 installation

Posted by Ludwig Stuyck on April 13, 2010

Visual Studio 2010 is out, and of course I installed it right away. During installation, it seemed that someone was getting really jealous ;)

Posted in Uncategorized | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.