Tuesday, June 26, 2012

[C#] Foreach loop remove comma at the end C#

A common problem in programming is listing off elements in a for, foreach, or while loop using commas or another character to delimit them for a string display. However, using the simple logic:

string += nextItem.toString() + ", ";

will always lead to having an extra ',' at the end, like this:

A, B, C, D,

The trick , for NET 3.0 and higher, can be done in just TWO lines of code!

1. Set up your enumerable list of items.
List<string> namesList = myList.Select(id=> getName(id).Name).ToList();

2. Join your list into a string!
myString = String.Join(", ", namesList );


Post a Comment