两个集合中的任何交集

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

Enumerable.Intersect可能就是你要找的东西。

来自MSDN:

 int[] id1 = { 44, 26, 92, 30, 71, 38 }; int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; IEnumerable both = id1.Intersect(id2); if(both.Any())... 
 bool intersects = collection1.Intersect(collection2).Any(); 

这假定集合成员的相等和哈希码的“适当”实现(例如基元的情况),否则您可以传递自定义IEqualityComparer

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

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

请查看http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx以及更多细节我刚刚找到http://www.codeproject.com/Articles/383749/How-在Csharp-Part-3-Csharp-Linq-in-d中工作是非常有帮助的。