Linq query for only the first N rows for each unique identifier

Let's say I have an IQueryable that will return a data type with an ID property (column).

I want to continue filtering my request (I do not want to evaluate the request) as follows:

For each unique ID from the main request, I want Take(n) , where n is some arbitrary number.

That is, I want to save only the first lines of n for each unique identifier.

I can get a great ID s ...

 var ids = query.Select(q => q.ID).Distinct(); 

and I can Take(n) with the rest of them, but I can’t say that I connect two:

 query = query.<FOR EACH DISTINCT ID>.Take(n); 

The accepted answer works, but slow for a large table. I wrote this question as a follow-up.

+6
source share
1 answer

You can do it as follows:

 query = query.GroupBy(q => q.ID).SelectMany(g => g.Take(n)); 

GroupBy combines records with identical ID s, allowing them to be processed as a group; SelectMany takes each group, limits the number of its members to n and returns the results back to one flat list.

+6
source

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


All Articles