Select top n rows in each group in EntityFramework

c# entity-framework

Question

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?

1
6
4/28/2014 9:03:27 AM

Accepted Answer

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.

11
4/28/2014 9:09:39 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow