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?
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists.
To perform the intersection operation on lists by using sets, you can convert the input lists to sets. After that, you can perform the set intersection operation using the intersection() method. Finally, you can convert the output set back into a list as follows.
The intersection should contain each common element only once. The order shouldn't matter, thus toSet is the most straightforward choice, but we can also use toList or another collector method.
LINQ Intersect operator is used to find the common elements between the two collections. Both of the collections must have the same data type, intersect operator which returns the set intersection it describes that the common elements present in two collections.
LINQ Intersect is an operator which comes under the Set Operators’ category. The Intersect operator is used to find the common elements in the collections, it requires two collections. LINQ Intersect returns the new sequence of an element which is the element that is common in both collections. It will be available only in Method syntax.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With