Saturday 3 June 2017

LINQ 11 Aggregate

Not all method based linq statements have an equivalent expression based counterpart. The Aggregate function is one of them

class Program
{
    static void Main(string[] args)
    {
        var nums = Enumerable.Range(1, 6);
        var result1 = nums.Aggregate((a, b) => a * b);
        Console.WriteLine($"6! = {result1}");

        var helloWorld = "hello world my name is Pawel".Split(' ');
        var result2 = helloWorld.Aggregate((sentance, word) => $"{word} {sentance}");
        Console.WriteLine(result2);
    }

}

Fairly straight forward, aggregate takes in a function that has a running tally and a parameter for each element in the collection. This let's you iterate over each one and return a single value.