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:
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:
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:
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:
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
0is 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.
Related reading
- Calculate Standard Deviation in TensorflowJS?
- Calculate the Cumulative Distribution Function CDF in Python
- Calculating AUC when using Vowpal Wabbit
- Calculating Nearest Match to Mean/Stddev Pair With LibSVM
- Calculate relative time in C#
- Call and Callvirt
- Calculating or Rows and Columns
- Calculating Pearson correlation and significance in Python

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.