Maxi
Maxi

Reputation: 173

LINQ - Select top 10% of elements

Using LINQ I have to select the top 10% of a List ordered (asc) by "Score" value. The model has Id and Score.

Example:

If I have 100 items and each of one has a score, i want them ordered by Score (asc) and only select the top 10 (10%)

What I've done so far:

var orderedList = (from Emps in db.Emps
                  orderby Emp.Score ascending
                  select Emp);

Then I have to count the orderedList and calculate the 10% and do another query. I want to be all in the same query if its possible.

How do I do this?

Upvotes: 3

Views: 4336

Answers (1)

Deadzone
Deadzone

Reputation: 814

You can use the Take(int count) extension method:

var result = values.OrderBy(t => t.Score).Take(values.Count * 10 / 100);

Or if you want to always take at least 1 value you can use Math.Ceiling:

var result = values.OrderBy(t => t.Score).Take((int) Math.Ceiling(values.Count * 10 / 100d));

Upvotes: 13

Related Questions