Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 735
Bongo Sharp Avatar asked May 16 '12 22:05

Bongo Sharp


People also ask

What is the intersection of two lists?

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.

Can I use intersection on list?

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.

How many times can the intersection of two classes contain common elements?

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.

How to find common elements between two collections in LINQ?

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.

What is LINQ intersect in Java?

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.


2 Answers

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())...
like image 164
Tim Schmelter Avatar answered Oct 09 '22 02:10

Tim Schmelter


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.

like image 34
BrokenGlass Avatar answered Oct 09 '22 00:10

BrokenGlass