Linq Aggregate to concatenate string with a comma<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Linq Aggregate to concatenate string with a comma

Posted on: April 1, 2013

If you have an array that you want to flatten into a string with a comma between each entry, you could use Linq with a one liner delegate to reach this goal.

string flatten = inputs.Aggregate((current, next) => string.Format("{0}, {1}", current, next))

This is quite powerful as you can see, you do not have to do validation to know if you have reach the last entry to not add a trailing comma. Without Linq and the aggregate function, you would have to loop and to verify this condition.

string flatten = string.Empty; for(int i = 0 ; i < inputs.Length ; i++) { if(i!=(i.Length-1)) { flatten += str + ", "; } else { flatten += str; } }

I don't know for you, but I found more easy to read the Aggregate method than the second snippet of code.