Have you ever wondered which one of Any, Contains or Exists you should use, and why they had to “give birth” to 3 of them like that! Now let’s take a look together at why. Let’s go!
Which one to use?
When working with ListContains method takes full advantage of their efficiency thanks to the way they’re designed internally (linear search based on index, using a basic for loop), guaranteeing the highest performance.
As for Exists, we can only use it with ListContains.
On the other hand, LINQ’s Any method can be applied to every kind of IEnumerable
However, that very flexibility is what makes Any run slower than Exists, because it has to create an enumerator + use foreach, plus there are some other costs on top (checking conditions to throw exceptions and so on).
What all three of these methods have in common is that they all search linearly with O(n) complexity.
A small note, Contains, if used carelessly, especially when you don’t clearly understand pass by reference vs pass by value (in Vietnamese), can easily blow up on you => don’t use Contains to check against a list or array of object (reference) type. Whereas with Any and Exists, when we write the comparison condition, we already have a clear idea of what we’re comparing.
For example
1 | using System.Collections.Generic; |
In summary
To wrap it up, if you know exactly what you’re comparing, if you’re comparing values, then prefer Contains, and conversely if you’re working with ListExists. And if you need a more general method that can be used on many different kinds of collections, Any will be the sensible choice.
Speed comparison
Here’s the speed comparison of the three against each other (list, array, ienumerable with 10000 elements of type int), look at columns 1, 2 and 5, taking ListAny as the baseline:
