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.

share|improve this question
add comment

2 Answers

up vote 8 down vote accepted
string.Join(", ", source
    .Select(foo=>foo /*Do something to append a string representation of foo*/));
share|improve this answer
    
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
add comment

Using Enumerable.Aggregate Linq method

source.Select(x=>x /*Do something if needed otherwise remove*/).Aggregate ( (a,b) => a + ", " + b);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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