LINQ查询只在第一个N行的每个唯一ID [英] Linq query for only the first N rows for each unique ID
问题描述
说我有一个的IQueryable
将返回一个数据类型与 ID
属性(列)。
Say I have an IQueryable
that will return a datatype with an ID
property (column).
我想进一步筛选我的查询(我不想评估查询的)如下:
I want to further filter my query (I don't want to evaluate the query) as follows:
有关每一个独特的 ID
从主查询,我想取(N)
,其中 N
一些任意数量。
For each unique ID
from the main query, I want to Take(n)
, where n
is some arbitrary number.
的也就是说,我只想保持第一 N
行针对每一个独特的ID。
That is, I want to only keep the first n
rows for each unique ID.
我可以得到不同的 ID的
...
I can get the distinct ID
's...
var ids = query.Select(q => q.ID).Distinct();
和我能取(N)
与他们的休息,但我难倒连接两个:
and I can Take(n)
with the rest of them, but I'm stumped on connecting the two:
query = query.<FOR EACH DISTINCT ID>.Take(n);
接受的答案工作,但对于一个大的表慢。我写这个问题作为后续
The accepted answer works, but is slow for a large table. I wrote this question as a follow-up.
推荐答案
您可以做到这样的:
query = query.GroupBy(q => q.ID).SelectMany(g => g.Take(n));
的
GROUPBY
汇集具有相同的记录 ID
S,让你处理它们作为一组; 的SelectMany
取各组,限制其成员人数为 N
,结果放回到一个单位名单。
The GroupBy
brings together the records with identical ID
s, letting you process them as a group; SelectMany
takes each group, limits the number of its members to n
, and puts the results back into one flat list.
这篇关于LINQ查询只在第一个N行的每个唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!