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?
Asked
Active
Viewed 5,883 times
4 Answers
21
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())...

Tim Schmelter
- 450,073
- 74
- 686
- 939
13
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
.

BrokenGlass
- 158,293
- 28
- 286
- 335
2
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();
}

Shaun Bowe
- 9,840
- 11
- 50
- 71
-
hardly worth it – BritishDeveloper Dec 12 '19 at 09:24
-1
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.
-
This isn't helpful to those looking for an answer to a specific question about linq. – Mick Mar 03 '22 at 06:49