Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top n values including duplicates with LINQ

Please consider this list:

City            Value
---------------------
City1             10
City2             20
City3             30
City4             40
City5             50
City6             60

If I want to get top 3 Values in Cities I can write this LINQ:

MyList.OrderByDescending(o=>o.Value).Take(3);

Now consider this list:

City            Value
---------------------
City1             10
City2             20
City3             30
City4             40
City5             50
City6             60
City7             60

I want a query that return all cities with top 3 highest values. For above list I want this result:

City            Value
---------------------
City7             60
City6             60
City5             50
City4             40

Thanks

like image 442
Arian Avatar asked Sep 14 '25 05:09

Arian


1 Answers

var result = MyList.GroupBy(o => o.Value)
                   .OrderByDescending(g => g.Key)
                   .Take(3)
                   .SelectMany(g => g)
                   .ToList();

This list will contain all cities with the top 3 highest values, sorted in descending order by value.

like image 154
AVTUNEY Avatar answered Sep 16 '25 19:09

AVTUNEY