Skip to content

Instantly share code, notes, and snippets.

@Reelix
Created September 25, 2018 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Reelix/64782b675b2e42912fb690c4eb9b3aa0 to your computer and use it in GitHub Desktop.
Save Reelix/64782b675b2e42912fb690c4eb9b3aa0 to your computer and use it in GitHub Desktop.
Finding the Median value of a List
class Program
{
static void Main(string[] args)
{
List<double> exampleOne = new List<double> { 1, 3, 3, 6, 7, 8, 9 };
List<double> exampleTwo = new List<double> { 1, 2, 3, 4, 5, 6, 8, 9 };
List<double> exampleThree = new List<double> { 0, 1, 2, 4, 6, 5, 3 };
double medianOne = exampleOne.Median();
double medianTwo = exampleTwo.Median();
double medianThree = exampleThree.Median();
Console.WriteLine(medianOne); // 6
Console.WriteLine(medianTwo); // 4.5
Console.WriteLine(medianThree); // 3
Console.ReadLine();
}
}
public static class ListExtensions
{
public static double Median(this List<double> inputList)
{
double[] xs = inputList.ToArray();
Array.Sort(xs);
return xs[xs.Length / 2];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment