#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 .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers