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.