相交LINQ查询LINQ

2023-09-02 10:43:08 作者:委屈时不说话一开口都是泪

如果我有一个IEnumerable,其中暴露的ClassA long类型的ID属性。 是否有可能使用LINQ查询来获得ClassA的所有实例ID为属于第二IEnumerable的?

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....)?

在这里原来是一个的IEnumerable&LT; ClassA的&GT; 和idsToFind是的IEnumerable&LT;长&GT;

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

推荐答案

是的。

至于其他人已经回答了,你可以使用其中,,但是这将是非常低效的大集。

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或上结果或更换加入群组加入 (该参数群组加入将是相同的)。

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).