How to calculate median in C#?

In my earlier articles, we have seen how to calculate mathematical statistical median, mean and mode in Sql Server. Now we will see how to calculate median in C# .Net.

In C#, you can write your own code for the median algorithm or you can use a third party library to calculate it. Both these methods have their advantages and disadvantages. You have to choose one of the methods based on your requirement. Let us see the methods one by one.

Write your own code

Coding the algorithm on your own in C# code to calculate median has its advantages and disadvantages. Writing your own code will avoid using 3rd party libraries. You can reduce the size and maintenance cost of your application. For example, you need to check the compatibility of the 3rd party libraries every time you upgrade its .net version and upgrade the libraries as well. However, coding yourself will increase the application development and testing time and resources.

Here is the sample c# code to calculate median.

public static double GetMedian(double[] arrSource)
{
    // Check if the array has values        
    if (arrSource == null || arrSource.Length == 0)
        throw new ArgumentException("Array is empty.");

    // Sort the array
    double[] arrSorted = (double[])arrSource.Clone();
    Array.Sort(arrSorted);

    // Calculate the median
    int size = arrSorted.Length; 
    int mid = size / 2;

    if (size % 2 != 0)
        return arrSorted[mid];

    dynamic value1 = arrSorted[mid];
    dynamic value2 = arrSorted[mid - 1];
    return (value1 + value2) / 2;
}
Calculate median in C# with your own code

Using 3rd party library

Using third party libraries helps you to reduce the coding time and testing time considerably. Here I am using the popular math library MathNet.Numerics from NuGet. Here is the sample code.

using MathNet.Numerics.Statistics;

namespace MyTecBits_Samples
{
    internal class StatisticsThirdParty
    {
        public static double GetMedian(double[] arrSource)
        {
            return arrSource.Median();
        }
    }
}

If your application uses several complex mathematical concepts, then it will be a good idea to use third party libraries like MathNet.Numerics.

If interested, you can checkout our online Mean, Median & Mode calculator developed in .NET.

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.