Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select top n rows in each group in EntityFramework

I'm trying to fetch recent contents of each type, currently I'm using something similar to the following code to fetch n records for each type

int n = 10;
var contents = Entities.OrderByDescending(i => i.Date);

IQueryable<Content> query = null;
for (int i = 1; i<=5; i++)
{
    if (query == null)
    {
        query = contents.Where(c => c.ContentTypeIndex == i).Take(n);
    }
    else
    {
        query = query.Concat(contents.Where(c => c.ContentTypeIndex == i).Take(n));
    }
}

One other solution can be creating an SP, but is it possible to do it by grouping in EF? If not, any cleaner solution?

like image 516
VahidNaderi Avatar asked Apr 28 '14 09:04

VahidNaderi


1 Answers

contents.Where(c => c.ContentTypeIndex >= 1 && c.ContentTypeIndex <= 5)
        .GroupBy(c => c.ContentTypeIndex)
        .SelectMany(g => g.Take(n));

Note: if you want to select all types of indexes, then you don't need where filter here.

like image 124
Sergey Berezovskiy Avatar answered Sep 21 '22 20:09

Sergey Berezovskiy