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.
enumerable. Any() is the cleanest way to check if there are any items in the list.
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.
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!
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:
Enumerable.Any
extension method to check for the existence of elements in the sequence.Enumerable.Count
extension method in comparisons against zero, as the following are semantically equivalent:
sequence.Count() == 0
!sequence.Any()
Enumerable.Count
extension method in comparisons against the “not zero” condition, as the following are semantically equivalent:
sequence.Count != 0
sequence.Any()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With