Aggregate

Aggregate allows you to specify a custom accumulation algorithm for implementing aggregations.

The following demonstrates how Aggregate can do the work of Sum:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 2, 3, 4 };
        int sum = numbers.Aggregate(0, (total, n) => total + n);  // 9
        Console.WriteLine(sum);

    }
}

The output:


9

Unseeded aggregations

You can omit the seed value when calling Aggregate.

The first element becomes the implicit seed, and aggregation proceeds from the second element.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3 };
        int x = numbers.Aggregate(0, (prod, n) => prod * n);  // 0*1*2*3 = 0
        int y = numbers.Aggregate((prod, n) => prod * n); //  1*2*3 = 6

        Console.WriteLine(x);

        Console.WriteLine(y);
    }
}

The output:


0
6
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.