#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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: