Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search two lists for at least one match with LINQ

Tags:

c#

linq

What is the best way (on average) to compare two lists with LINQ (query syntax or otherwise)

var A = new [] { 1, 2, 3, ... };
var B = new [] { 4, 1, 5, ... };

bool match = 
    // Some LINQ expression

such that match will be true when at least one element in the first list (1 in this case) equals an element from the second? I don't need to know how many matches there were, or even which one was matched, just that there was at least one match.

like image 331
Eric B Avatar asked Jul 01 '13 18:07

Eric B


4 Answers

Sure there is.

A.Intersect(B).Any();

Intersect is always useful in the least expected circumstances.

like image 111
It'sNotALie. Avatar answered Nov 05 '22 17:11

It'sNotALie.


You could use Intersect, but that would calculate all matches, which you don't need. So Any is better, since it will short-circuit:

bool match = A.Any(a => B.Any(b => b == a));
like image 40
McGarnagle Avatar answered Nov 05 '22 15:11

McGarnagle


you can also use

A.Any(x => B.Contains(x))
like image 3
COLD TOLD Avatar answered Nov 05 '22 16:11

COLD TOLD


You're looking for a combination of Intersect and Any

bool match = A.Intersect(B).Any();
like image 2
Simon Belanger Avatar answered Nov 05 '22 17:11

Simon Belanger