HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

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

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqstatementbetterlistsoverlapbetweentwofindwhichthere

Problem

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?

Which is more readable?

Solution

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.


Which is more readable?

In my opinion two are about equally readable, although I would change #2 to be:

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


As far as performance, #1 will probably perform better in most cases, since it will dump all of one list into a hash table and then do an O(1) lookup for each element in the other list. Two exceptions to this that I can think of are (1) if the lists are very small, then building the hash table data structure might not be worth the overhead and (2) option 2 can theoretically return without having considered every element in either list. If the lists are large lazy enumerables and you expect this to return true in most cases then this could lead to a performance increase.

Code Snippets

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

Context

StackExchange Code Review Q#13127, answer score: 6

Revisions (0)

No revisions yet.