It's easy to calculate
median[
^], because it's a middle/central value
* of ordered list.
* - for even number of values - it's an average of two values from middle of ordered list
Follow the above link for further details.
int[] ages = {100,22,13,43,25,61,17,80,29};
bool isEvenNumberOfValues = ages.Length % 2 == 0;
int toSkip = isEvenNumberOfValues ? (ages.Length/2)-1 : ages.Length/2;
int toTake = isEvenNumberOfValues ? 2 : 1;
var result = ages.OrderBy(x=>x).Skip(toSkip).Take(toTake).Average();
Console.WriteLine("Median for: [{0}] is {1}", string.Join(",", ages.OrderBy(x=>x)), result);
All you need to do is to create
Median
function (based on above code). A
Median
function have to:
1. take an array of numbers as an input argument
2. return double
Another implementation of Median function, you'll find here:
How to: Add Custom Methods for LINQ Queries (C#) | Microsoft Docs[
^]