Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get top 3 from each "by group" in LINQ?

Tags:

linq

I have a table that looks something like:

Favourite color | Favourite Food | Favourite Dance | Date

Now I want to group by favourite color and favourite food. Then take top 3 in each group ordered by date (the latest). I just cannot seem to get it to work using LINQ.

like image 749
cc81 Avatar asked Feb 24 '23 03:02

cc81


1 Answers

Like this:

from x in thingy
group x by new { x.Color, x.Food } into g
select new {
    g.Key.Color, 
    g.Key.Food, 
    Items = g.OrderByDescending(x => x.Date).Take(3) 
}
like image 113
SLaks Avatar answered Feb 25 '23 16:02

SLaks