Functional programming with Linq — IEnumerable.Aggregate

As I was learn­ing func­tion­al pro­gram­ming with F# I came across the List.reduce func­tion which iter­ates through a list and builds up an accu­mu­la­tor val­ue by run­ning anoth­er func­tion against each ele­ment in the list.

Back to the more famil­iar C# ter­ri­to­ry, LINQ has intro­duced some func­tion­al fea­tures to C# and one of these is the Aggre­gate func­tion on IEnumerable<T> which works in the same way as the List.reduce func­tion.

In the fol­low­ing exam­ple, you can use the Aggre­gate func­tion to built up a com­ma sep­a­rat­ed string from an array of string:

var strings = new List<string> { "Jack", "Jill", "Jim", "Joe", "Jane" };
// this returns "Jack, Jill, Jim, Joe, Jane"
var comSeparatedStrings = strings.Aggregate((acc, item) => acc + ", " + item);