#147 – Getting the Average of an Array of Numbers

If you have an array containing a collection of numeric values, you can get the average (mean) using the Average method.

            int[] scores = { 89, 98, 72, 100, 83 };

            double avg = scores.Average();      // 88.4

The Average method is an extension method, applied to Array by virtue of its implementation of the IEnumerable interface.  It’s part of the System.Linq namespace, so you’ll need a using statement for this namespace.  Average is available in .NET 4 and 3.5.

Average will work for arrays containing any numeric type.

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

One Response to #147 – Getting the Average of an Array of Numbers

  1. Pingback: #150 – Other Aggregate Functions You Can Apply to Numeric Arrays « 2,000 Things You Should Know About C#

Leave a comment