How do I get a percentile from a list in CSharp?

Chielle picture Chielle · Sep 12, 2011 · Viewed 7.3k times · Source

I'm creating a program where I would like to get the percentile of score x out of a list(List results). I know that the formula is [(A + (0.5) B) / n] * 100 where 'A' = # of scores lower than score x, 'B' = # of scores equal to score x and 'n' = total number of scores.

My problem is, I can't manage to sort the entire list from highest to lowest, and I can't manage to find the number of scores which are equal to x.

Answer

Jon Skeet picture Jon Skeet · Sep 12, 2011

It sounds like LINQ would be useful to you:

int equal = tests.Count(tests => test.Score == x);
int less = tests.Count(tests => test.Score < x);

int percentile = (200 * less + 100 * equal) / (tests.Count * 2);

(I've changed the order of division and multiplication and scaled everything by two in order to reduce the impact of integer division.)