Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 811
Adam Avatar asked Mar 27 '09 19:03

Adam


People also ask

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.

What does any () do in C#?

The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned.

Can you use Linq on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!


1 Answers

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()
like image 196
casperOne Avatar answered Oct 02 '22 01:10

casperOne