Alex Rivera | Logout

Determine if an IEnumerable<T> contains any object of another IEnumerable<T>

Asked 2009-03-27T19:19:54.453
19

I have 2 IEnumerable<int>

IEnumerable<int> x;
IEnumerable<int> y;

What is the best best way to determine if any int in y is present in the x?
Currently I'm using:

return x.Intersect<int>(y).Count() > 0;

Would it be significantly faster to loop through and test each individually?

foreach (int i in x)
{
    foreach (int j in y)
    {
        if (i == j) return true;
    }
}
return false;

The lists are relatively light, with not more than 50 ints in x and 4 in y if that matters in the consideration.

Edit
Report

1 Answer

31

It would be fastest to use the Any method instead of the Count method:

return x.Intersect<int>(y).Any();

This assumes that the IEnumerable<int> implementation doesn't also implement ICollection<int>. In that case, Count (in the case where IEnumerable<T> implements ICollection<T>) is an O(N) operation while Any is always an O(1) operation. (as it only checks for a single element). However, the behavior of Count is an implementation detail, and you shouldn't rely on that.

I've written about this more in-depth in a blog post that goes into detail about when to use Count() vs. Any(). In summary:

  • DO use Enumerable.Any extension method to check for the existence of elements in the sequence.
  • DO NOT use Enumerable.Count extension method in comparisons against zero, as the following are semantically equivalent:
    • sequence.Count() == 0
    • !sequence.Any()
  • DO NOT use the Enumerable.Count extension method in comparisons against the “not zero” condition, as the following are semantically equivalent:
    • sequence.Count != 0
    • sequence.Any()
answered 2009-03-27T19:22:05.040

Your Answer