15

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?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Bongo Sharp
  • 9,450
  • 8
  • 25
  • 35

4 Answers4

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