我认为这需要 O(A x B)
时间来执行。
(其中 A 是 collectionA 的大小,B 是 collectionB 的大小)
我说的对吗?
IEnumerable<A> GetMatches(IEnumerable<A> collectionA, IEnumerable<B> collectionB)
{
foreach (A a in collectionA)
foreach (B b in collectionB)
if (a.Value == b.Value)
yield return a;
}
有没有更快的方法来执行这个查询? (也许使用 LINQ?)
最佳答案
不幸的是,
Enumerable.Intersect
将无法工作,因为您正在与两种不同的类型(A
和 B
)进行比较。
这将需要一些单独处理才能获得有效的 Intersect 调用。
您可以分阶段进行:
IEnumerable<A> GetMatches(IEnumerable<A> collectionA, IEnumerable<B> collectionB)
where A : ISomeConstraintWithValueProperty
where B : ISomeOtherConstraintWithSameValueProperty
{
// Get distinct values in A
var values = new HashSet<TypeOfValue>(collectionB.Select(b => b.Value));
return collectionA.Where(a => values.Contains(a.Value));
}
请注意,如果 collectionB
包含重复项(但不包含 collectionA),这将返回重复项,因此它的结果与循环代码略有不同。
如果您想要独特的匹配项(只返回一个),您可以将最后一行更改为:
return collectionA.Where(a => values.Contains(a.Value)).Distinct();
关于c# - 如何在不同类型的集合之间进行匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7124461/