C#
median calculation
programming tutorial
data analysis
.NET

Calculate the median in C#

Codemia Knowledge Hub ·

To calculate a median in C#, sort the data, then take the middle value (odd count) or the average of the two middle values (even count). Also decide how to handle empty input, whether you may mutate the caller's collection, and return a double so integer input can still produce a fractional median.

For a sorted sequence:

  • if the count is odd, the median is the middle value
  • if the count is even, the median is the average of the two middle values

So [1, 3, 5] has median 3, and [1, 3, 5, 7] has median 4. The definition assumes ordered data, which is why sorting comes first.

A reusable Median method

This method accepts a sequence of double values and returns a double median:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5Console.WriteLine(Statistics.Median(new[] { 7.0, 1.0, 3.0 }));      // 3
6Console.WriteLine(Statistics.Median(new[] { 1.0, 3.0, 5.0, 7.0 })); // 4
7
8public static class Statistics
9{
10    public static double Median(IEnumerable<double> values)
11    {
12        double[] sorted = values.OrderBy(x => x).ToArray();
13
14        if (sorted.Length == 0)
15        {
16            throw new InvalidOperationException("Cannot compute median of an empty sequence.");
17        }
18
19        int middle = sorted.Length / 2;
20
21        if (sorted.Length % 2 == 1)
22        {
23            return sorted[middle];
24        }
25
26        return (sorted[middle - 1] + sorted[middle]) / 2.0;
27    }
28}

It is clear, safe and appropriate for ordinary application code.

Why return double

Even with integer input, an even-length median may not be an integer: [1, 2, 100, 101] has a median of 51. Returning double is the least surprising API. Keeping everything as int risks losing the fractional part to integer division, which is wrong for even counts:

csharp
int wrong = (3 + 4) / 2; // 3, not 3.5

Dividing by 2.0 or using a floating-point return type avoids this.

Not mutating the caller's data

Sorting the caller's List or array in place changes their data, which should be a deliberate choice. OrderBy(...).ToArray() copies the data into a sorted array and leaves the original untouched.

If mutation is acceptable and performance is critical, an in-place sort avoids the extra allocation:

csharp
1using System;
2
3int[] data = { 9, 2, 5, 1 };
4Array.Sort(data);

Be clear about which behavior your method promises.

Very large datasets and streams

Sorting is O(n log n), which is fine for many uses. For a huge dataset where you do not need a full sort, selection algorithms can find the median in linear time on average. The sorted approach is still the practical default for ordinary business or analytics code because it is simple and reliable.

For streaming data, a common solution is maintaining two heaps so the median can be updated incrementally.

An overload for integers

If you often work with integers, a small overload keeps call sites clean and still returns correct fractional results:

csharp
1using System.Collections.Generic;
2using System.Linq;
3
4public static double Median(IEnumerable<int> values)
5{
6    return Statistics.Median(values.Select(x => (double)x));
7}

Mistakes to avoid

  • Taking the middle element without sorting first. The median depends on order, not insertion sequence.
  • Using integer division for even-length collections, which silently truncates the result.
  • Ignoring empty input. Silently returning 0 is usually worse than throwing a clear error.
  • Sorting the caller's collection in place without saying so, which can cause bugs far from the median code.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design