Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I often have code that looks like this:

boolean isFirst = true;
var builder = new StringBuilder();

foreach (var foo in source) { //source might be empty
   if (isFirst) {
      isFirst = false;
   else {
      builder.Append(", ");

   //Do something to append a string representation of foo to builder
return builder.ToString();

This works, but it looks unnecessarily complicated. I suspect there might be a better way to write this code. LINQ's Aggregate seems really close, but the types I've used (StringBuilder and a custom class) don't really fit Aggregate.

If instead of foreach, I use for, then I can just check for i=0, which removes the need for the extra variable, but it still doesn't feel right.

Repeating the code for the first iteration outside the cycle seems even worse as it would be a violation of the DRY principle.


locked by Jamal Aug 10 at 0:07

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

2 Answers 2

up vote 8 down vote accepted
string.Join(", ", source
    .Select(foo=>foo /*Do something to append a string representation of foo*/));
BTW, in .Net 4.0, you don't need that ToArray(). –  svick Dec 9 '12 at 17:25
thanks for suggestion, forgot about it –  almaz Dec 9 '12 at 17:36

Using Enumerable.Aggregate Linq method

source.Select(x=>x /*Do something if needed otherwise remove*/).Aggregate ( (a,b) => a + ", " + b);

Not the answer you're looking for? Browse other questions tagged or ask your own question.