Looking for .net Answers? Try Ask4KnowledgeBase
Looking for .net Keywords? Try Ask4Keywords

.NET Framework Aggregate (fold)


Generating a new object in each step:

var elements = new[] {1,2,3,4,5};

var commaSeparatedElements = elements.Aggregate(
    seed: "",
    func: (aggregate, element) => $"{aggregate}{element},");
Console.WriteLine(commaSeparatedElements);  //1,2,3,4,5,

Using the same object in all steps:

var commaSeparatedElements2 = elements.Aggregate(
    seed: new StringBuilder(),
    func: (seed, element) => seed.Append($"{element},"));
Console.WriteLine(commaSeparatedElements2.ToString());  //1,2,3,4,5,

Using a result selector:

var commaSeparatedElements3 = elements.Aggregate(
    seed: new StringBuilder(),
    func: (seed, element) => seed.Append($"{element},"),
    resultSelector: (seed) => seed.ToString());
Console.WriteLine(commaSeparatedElements3);  //1,2,3,4,5,

If a seed is omitted, the first element becomes the seed:

var seedAndElements = elements.Select(n=>n.ToString());
var commaSeparatedElements4 = seedAndElements.Aggregate(
    func: (aggregate, element) => $"{aggregate}{element},");

Console.WriteLine(commaSeparatedElements4);  //12,3,4,5,