问题
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