#148 – Getting the Average of an Array of Custom Objects

If you want to calculate the average (mean) of a collection of objects stored in an array, you can use the IEnumerable.Average method.

The Average method allows passing in an indication of the function that should be used to calculate the numeric value from each object, which will be used in generating the average.  This function takes an object whose type matches the type of the array as an input parameter and returns a numeric value, used in generating the average.  It will be called once for each element of the array.

You could define a static function and pass a delegate to that function.

        static int AgeOf(Person p)
        {
            return p.Age;
        }

        // Example of calling Average on Person[] array
        double avgAge = folks.Average((Func<Person,int>)AgeOf);

Alternatively, you could use a lambda expression, avoiding the need to define a separate function.

            double avgAge = folks.Average(person => person.Age);
Advertisement

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 )

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: