# Better way to write this fold operation?

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 '14 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.

string.Join(", ", source

BTW, in .Net 4.0, you don't need that ToArray(). –  svick Dec 9 '12 at 17:25
Using Enumerable.Aggregate Linq method
source.Select(x=>x /*Do something if needed otherwise remove*/).Aggregate ( (a,b) => a + ", " + b);