Search code examples
c#linqlinq-to-entitiesc#-7.0

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


Solution

  • 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.