C # Check if any int in a list matches any int in another list

Sorry if this is an obvious question, but I can not find the answer.

Say I have the following:

var list1 = new List<int>{1,2,3};
var list2 = new List<int>{3,5,6};

How can I see if any element of list1 is in list2? Therefore, in this case, I want to return true, because 3 in both.

Performing nested loops will not work for me, so it would be ideal if there was:

list1.HasElementIn(list2);
+3
source share
1 answer

Use Enumerable.Intersect - it creates the intersection of both sequences. If the intersection is not empty, then there is some element that exists in both sequences:

bool isAnyItemInBothLists = list1.Intersect(list2).Any();

- Intersect , , - . , .

+12

All Articles