LINQ Aggregate for Comma-Separated Lists of Values

A couple of days ago, while pairing with my colleague Alexei on bug fixes to a new feature, we came across a bit of code that attempted to take an integer array and construct a string with a comma-delimited list of the numbers from it. The existing code didn’t quite work, so we wrote a basic for-each loop and used ReSharper to see what LINQ alternative it might construct. Here’s what ReSharper came up with:

int[] numbers = new[] {1, 5, 8, 26, 35, 42};
var result = numbers.Aggregate("", (current, item) => current + item.ToString() + ",");

Before ReSharper served this up, I wasn’t familiar with the Aggregate operator. When I checked out 101 LINQ Samples for it, the vast majority of the examples used numbers.