Bongo Sharp
Bongo Sharp

Reputation: 9610

Any Intersection in Two Collections

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?

Upvotes: 15

Views: 6612

Answers (4)

Marek Pio
Marek Pio

Reputation: 127

I found two ways

IsUnaddressedDeviceAvailable = Devices.Any(d => unaddressedDeviceIDs.Any(u => u == d.DeviceId));
IsUnaddressedDeviceAvailable = Devices.IntersectBy(unaddressedDeviceIDs, x => x.DeviceId).Any();

the second version looks better for me.

Upvotes: 0

Shaun Bowe
Shaun Bowe

Reputation: 10008

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();
}

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160862

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.

Upvotes: 13

Tim Schmelter
Tim Schmelter

Reputation: 460098

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

Upvotes: 21

Related Questions