交叉LINQ查询 [英] Intersect LINQ query

查看:21
本文介绍了交叉LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 IEnumerable,其中 ClassA 公开了一个 long 类型的 ID 属性.是否可以使用 Linq 查询获取 ID 属于第二个 IEnumerable 的 ClassA 的所有实例?

If I have an IEnumerable where ClassA exposes an ID property of type long. Is it possible to use a Linq query to get all instances of ClassA with ID belonging to a second IEnumerable?

换句话说,这能做到吗?

In other words, can this be done?

IEnumerable<ClassA> = original.Intersect(idsToFind....)?

其中 original 是 IEnumerable,idsToFind 是 IEnumerable.

where original is an IEnumerable<ClassA> and idsToFind is IEnumerable<long>.

推荐答案

是.

正如其他人回答的那样,您可以使用Where,但对于大型集合来说效率极低.

As other people have answered, you can use Where, but it will be extremely inefficient for large sets.

如果担心性能,您可以致电加入:

If performance is a concern, you can call Join:

var results = original.Join(idsToFind, o => o.Id, id => id, (o, id) => o);

如果 idsToFind 可以包含重复项,您需要对 ID 或结果调用 Distinct() 或替换 Join使用 GroupJoin(GroupJoin 的参数将是一样的).

If idsToFind can contain duplicates, you'll need to either call Distinct() on the IDs or on the results or replace Join with GroupJoin (The parameters to GroupJoin would be the same).

这篇关于交叉LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆