# Which linq statement is better to find there is an overlap between two lists of ints?

I'm wondering about the difference between these two linq statements

bool overlap = GetMyListA().Intersect(GetMyListB()).Any(); // 1.


vs

bool overlap = GetMyListA().Any(i => GetMyListB().Contains(i)); // 2.


Will statement 2. call GetMyListB() for each item in ListA?

• Both will yield the same result (assuming there are no side-effects in GetMyListA() or GetMyListB()). I'd say 1 is the most readable and 2 the most logical. Jun 27 '12 at 15:10
• Is there any difference in performance? Would 'GetMyListB()' be called multiple times?
– Kim
Jun 27 '12 at 15:18
• Assuming you're working with lists, there would likely be a performance difference. Using Intersect() would utilize hash sets to determine uniqueness. The other code would perform linear searches through list B and would return on the first match (and yes, GetMyListB() will be called for each item in list A). Jun 27 '12 at 15:40
• It really depends on the linq provider and the types of the objects. This question would be better for stackoverflow though. Jun 27 '12 at 16:56
• A similar question of me: stackoverflow.com/questions/10110013/… Short answer: In LINQ-To-Objects they are equal, but the first is more readable (imho): Jul 13 '12 at 22:30

Assuming LINQ to objects (i. e. these are in-memory collections not LINQ to Entities IQueryables or something):

Will statement 2. call GetMyListB() for each item in ListA?

Yes. If you want to avoid this, you'll have to store the result of GetMyListB() outside the function.

bool overlap = GetMyListA().Any(GetMyListB().Contains); // 2.