Any Intersection in Two Collections
Asked Answered
B

4

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?

Bougainville answered 16/5, 2012 at 22:5 Comment(1)
"Elegant" is a very subjective word. Also, it would have been better to see the code. A description is always vague.Annatto
E
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())...
Eurythmic answered 16/5, 2012 at 22:6 Comment(0)
O
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.

Outward answered 16/5, 2012 at 22:7 Comment(0)
E
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();
}
Exarchate answered 16/9, 2016 at 13:50 Comment(1)
hardly worth itWeka
V
0

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.

Vixen answered 22/5 at 7:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.