两个集合中的任何交集

Bon*_*arp 13 c# linq collections

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

Tim*_*ter 17

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())...
Run Code Online (Sandbox Code Playgroud)


Bro*_*ass 12

bool intersects = collection1.Intersect(collection2).Any();
Run Code Online (Sandbox Code Playgroud)

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