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?
Any Intersection in Two Collections
Asked Answered
"Elegant" is a very subjective word. Also, it would have been better to see the code. A description is always vague. –
Annatto
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())...
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
.
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();
}
hardly worth it –
Weka
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.
© 2022 - 2024 — McMap. All rights reserved.