Select the top n rows in each group in EntityFramework

I am trying to get the last content of each type, currently I am using something similar to the following code to extract 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));
    }
}

Another solution could be to create an SP, but is it possible by grouping in EF? If not, is there any cleaning solution?

+4
source share
1 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, you do not need a filter where.

+10
source

Source: https://habr.com/ru/post/1538365/


All Articles