Created
September 25, 2018 02:15
-
-
Save Reelix/64782b675b2e42912fb690c4eb9b3aa0 to your computer and use it in GitHub Desktop.
Finding the Median value of a List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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