Last active
August 29, 2015 14:00
-
-
Save hidori/11085259 to your computer and use it in GitHub Desktop.
Median
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
double Median<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) | |
{ | |
if (!source.Any()) throw new InvalidOperationException(); | |
var sorted = source.OrderBy(selector); | |
var count = (int)(sorted.Count()); | |
int index = count / 2; | |
if (count % 2 == 0) | |
{ | |
return new [] { selector(sorted.ElementAt(index)), selector(sorted.ElementAt(index - 1)) }.Average(); | |
} | |
else | |
{ | |
return selector(sorted.ElementAt(index)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment