This is a continuation of this issue.
TL; DR:
Question:
I want to filter the query to save only the first n lines for each unique identifier.
Answer:
query = query.GroupBy(q => q.ID).SelectMany(g => g.Take(n));
The problem with this answer is that for 80,000 + lines, query evaluation takes much longer than filtering by iteration ( foreach ) (at least twice as slow). Considering the SQL generated by this answer, CROSS APPLY , most likely for SelectMany() .
This link describes what CROSS APPLY does:
The APPLY statement allows you to join two table expressions; the correct table expression is processed each time for each row from the left table expression.
In short, I'm looking for a filter query that efficiently collects the top N rows for each unique ID .
A Linq solution with explained SQL would be ideal.
source share