Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check if any int in list matches any int in another list [duplicate]

Tags:

c#

list

I apologize if this is an obvious question, but I cannot 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 contained in list2? So in this case I want to return true because 3 is in both.

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

list1.HasElementIn(list2);
like image 585
girlcode Avatar asked Dec 09 '22 10:12

girlcode


1 Answers

Use Enumerable.Intersect - it produces intersection of both sequences. If intersection is not empty, then there some item which exists in both sequences:

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

One thing to note - thus Intersect is a deferred streaming operator, then you will get result as soon as any common item will be found. So, you don't need to wait until complete intersection will be computed.

like image 122
Sergey Berezovskiy Avatar answered Dec 11 '22 09:12

Sergey Berezovskiy