Any Intersection in Two Collections

こ雲淡風輕ζ 提交于 2019-12-19 05:14:38

问题


i have to find out whether or not two collections have any intersection, the way that i did that is using LINQ's "Join" to get the Intersection of the two collections and then i use "Any". But i wonder, is there other more "elegant" way of doing this?


回答1:


Enumerable.Intersect is probably what you're looking for.

From 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())...



回答2:


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

This assumes an "appropriate" implementation of equality and hashcode for the members of your collection (that's e.g. the case for primitives), otherwise you can pass a custom IEqualityComparer.




回答3:


Here is an extension method that we use:

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



回答4:


Please have a look http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx and more in detail I just found http://www.codeproject.com/Articles/383749/How-does-it-work-in-Csharp-Part-3-Csharp-Linq-in-d will be quite helpful.



来源:https://stackoverflow.com/questions/10627419/any-intersection-in-two-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!