Intersect
is okay, but as others have said I wouldn't call .Count()
on the result.
The reason is that Intersect does not create the intersection of the two lists. It creates an IEnumerable
that is capable of enumerating that intersection, but it doesn't actually enumerate those results yet. Most of the work is deferred until the time when you finally iterate over this enumeration.
The problem with Count
is that it does iterate over the entire enumeration. So not only does it always count all the results, but it causes all of the work involved in computing those results to run as well.
Calling Any
instead will be very fast by comparison, because you will compute at most one intersection result before returning. Of course, in the case where there are no matches it will still need to iterate the entire list. However, that's no worse off than you were before. In fact, it's still faster because as Jon Skeet mentioned, the Intersect
function uses a HashSet to compute the results rather than iterating over everything. Your best and average cases are improved tremendously.
It's like the difference between these two snippets:
int count = 0;
foreach (int i in x)
{
foreach (int j in y)
{
if (i==j) count++;
}
}
return (count > 0);
.
// this one should look familiar
foreach (int i in x)
{
foreach (int j in y)
{
if (i==j) return true;
}
}
return false;
Obviously the 2nd is much faster on average. The performance of Any()
would be analogous (not the same as, thanks to the HashSet) the 2nd snippet, while Count()
would be analogous to the first.