2012-05-16 145 views
11

我必須找出兩個集合是否有任何交集,我這樣做的方式是使用LINQ的「Join」來獲得兩個集合的交集,然後使用「Any」。但我想知道,還有其他更「優雅」的方式嗎?兩個集合中的任何交集

回答

14

Enumerable.Intersect可能是你在找什麼。

從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())... 
+0

謝謝!對此,我真的非常感激 :) –

11
bool intersects = collection1.Intersect(collection2).Any(); 

這是假定「適當」的實施爲你收集的成員平等的hashCode(這是例如用於原語的情況下),否則,你可以通過自定義IEqualityComparer

1

這裏是我們使用的擴展方法:

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