#149 – Using IEnumerable.Aggregate to Perform a Calculation Based on All Elements in an Array

IEnumerable.Average can be used to perform an average across all elements in an array.  Instead of doing an average, we can perform our own custom calculation across all elements, using the IEnumerable.Aggregate function.

Aggregate works by specifying a function that will get called once for each element in the array (except for the first element).  The function’s arguments are:

  • On 1st pass: 1st and 2nd elements are passed to the function
  • On 2nd thru (n-1)th pass: result of previous pass is passed as 1st parameter, next element as 2nd parameter

The return value is used to store the result of your aggregate function and is passed back to the function on the next pass.

Here’s an example:

        public static Person CombinePeople(Person prevResult, Person next)
        {
            return new Person(prevResult.FirstName + next.FirstName,
                prevResult.LastName + next.LastName,
                prevResult.Age + next.Age);
        }

        // Example of calling Aggregate
        Person pCombined = folks.Aggregate((Func<Person,Person,Person>)CombinePeople);