C# 两个集合中的任意交点

C# 两个集合中的任意交点,c#,linq,collections,C#,Linq,Collections,我必须找出两个集合是否有交集,我这样做的方式是使用LINQ的“Join”来获得两个集合的交集,然后使用“any”。但我想知道,还有其他更“优雅”的方式吗?可能就是你想要的 从MSDN: int[] id1 = { 44, 26, 92, 30, 71, 38 }; int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; IEnumerable<int> both = id1.Intersect(id2); if(both.Any())... int[]

我必须找出两个集合是否有交集,我这样做的方式是使用LINQ的“Join”来获得两个集合的交集,然后使用“any”。但我想知道,还有其他更“优雅”的方式吗?

可能就是你想要的

从MSDN:

int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
IEnumerable<int> both = id1.Intersect(id2);
if(both.Any())...
int[]id1={44,26,92,30,71,38};
int[]id2={39,59,83,47,26,4,30};
IEnumerable两者=id1.相交(id2);
如果(都是.Any())。。。

这假定为集合成员“适当”地实现了相等和哈希代码(例如原语),否则您可以传递一个自定义的
IEqualityComparer
,请看一看,我刚才发现的更多细节将非常有用。

这里是我们使用的扩展方法:

public static bool IntersectAny<T>(this IEnumerable<T> first, IEnumerable<T> second, IEqualityComparer<T> comparer = null) {
    return first.Intersect(second, comparer).Any();
}
public static bool IntersectAny(此IEnumerable first,IEnumerable second,IEqualityComparer comparer comparer=null){
返回first.Intersect(second,comparer.Any();
}

谢谢!我真的很感激:)不值得
public static bool IntersectAny<T>(this IEnumerable<T> first, IEnumerable<T> second, IEqualityComparer<T> comparer = null) {
    return first.Intersect(second, comparer).Any();
}