Find the Mean of an Array of Numbers in C#

Let’s say you have an array of numbers and want to be able to find the mathematical mean of those numbers in C#. To my knowledge, the .NET Framework does not have a function to do this built in. (Please let me know if you know otherwise.) So I built a method that does this. It builds on this post, which explains how to get the sum of an array. Getting the mean basically comes down to finding the sum and then dividing it by the number of elements in the array.

public static double Mean(params double[] values)
{
    return Sum(values) / (double)values.Length;
}

One Response to “Find the Mean of an Array of Numbers in C#”

  1. Actually there is now a LINQ command for getting both the average (MEAN) and the Sum. Simply target the 3.5 framework (project > settings), as a using System.Linq to the top of the file, and you will then have the Average() and Sum() extension methods added to your array. Benig LINQ, this works with any IEnumerable.

Leave a Reply