CSharp - LINQ Aggregate

Introduction

The Aggregate operator performs a user-specified function on each element of an input sequence.

It passes in the function's return value from the previous element and returns the return value of the last element.

Prototypes

There are two prototypes we cover. The First Aggregate Prototype

public static T Aggregate<T>(
  this IEnumerable<T> source,
  Func<T, T, T> func);

In this version of the prototype, the Aggregate operator calls the func method on each, passing the return value from the previous element as the first argument and the element itself as the second argument.

Finally storing the value returned by func into an internal accumulator, which will then be passed to the next element.

The first element will be passed itself as the input value to the func method delegate.

The second prototype of the Aggregate operator starts with a seed value that will be the input value for the first invocation of the func method delegate instead of the first element.

public static U Aggregate<T, U>(
  this IEnumerable<T> source,
  U seed,
  Func<U, T, U> func);

Exceptions

  • ArgumentNullException is thrown if the source or func argument is null.
  • InvalidOperationException is thrown if the input source sequence is empty, only for the first Aggregate prototype, where no seed value is provided.

The following code calculates the factorial for the number 5.

A factorial is the product of all positive integers less than or equal to some number.

The factorial of 5 is the product of all positive integers less than or equal to 5.

5!, pronounced 5 factorial, will be equal to 1 * 2 * 3 * 4 * 5.

We use the Range operator and the Aggregate operator to calculate this.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from  w  w  w .jav  a2  s  . c o  m*/
{
    static void Main(string[] args)
    {
            int N = 5;
            IEnumerable<int> intSequence = Enumerable.Range(1, N);
    
            //  we will just output the sequence so all can see it.
            foreach (int item in intSequence)
              Console.WriteLine(item);
    
            //  Now calculate the factorial and display it.
            //  av == aggregated value, e == element
            int agg = intSequence.Aggregate((av, e) => av * e);
            Console.WriteLine("{0}! = {1}", N, agg);
    }
}

Result

Related Topics