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:

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

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

  1: List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
  2: 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:

  1: string commaSeparatedListOfGroups = string.Join(",", allRelatedGroups.Select(g => g.Id.ToString()).ToArray());
May 7, 2010 05:14 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading