Skip to content

Instantly share code, notes, and snippets.

@hidori
Last active August 29, 2015 14:00
Show Gist options
  • Save hidori/11085259 to your computer and use it in GitHub Desktop.
Save hidori/11085259 to your computer and use it in GitHub Desktop.
Median
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