A surprising question - I find the intent of list.Any()
to be much clearer than the intent of list.Count()!=0
.
Intent means: If you read someones code (and you didn't write it yourself), is it completely obvious what the programmer wants to achieve and why it written written like it is? If a common problem is solved in a needlessly complex way, you immediately gets suspicious and wonder why the developer didn't use the simple way. You look through the code and try to see if you have missed something. You are afraid to change the code because you worry there is some side effect you are missing and changing it may cause unexpected problems.
The intent of using the Any()
method is completely clear - you want to know if there are any elements in the list or not.
The intent of the expression Count()!=0
on the other hand is not obvious for the reader. It is of course not hard to see that the expression tells you if the list is empty or not. The questions arises because you write it this particular way rather than using the standard method. Why do you use Count()
explicitly? If you really just need to know if there are any elements in a list, why do you want to count the whole list first? As soon as you reach 1 you already have have your answer. If the source was an iterator over a large (perhaps infinite) collection or is translated to sql, it could make a big difference performance wise. So maybe the explicit use of Count() is to force a deferred query to execute or to traverse an iterator?
But the source is actually a List<T>
where Count()
is O(1) and has no side effects. But if the code relies of this property of List<T>
, then why not use the Count
-property which more clearly indicate that you expect an O(1) operation with no side effects?
As it is written, list.Count()!=0
does exactly the same as list.Any()
except it is needlessly more complex and the intent is unclear.
Any()
is less clear:Any()
seems more clear to me, especially with a lambda-condition. Translating code to English in my head,if(MyList.Count(o => o > 10) > 0)
becomes "Is the number of items greater than 10 more than 0?" whereasif(MyList.Any(o => o > 10))
becomes "Are there any items greater than 10?"Any
isExists
. The Linq name is probably more inspired by Haskell and Python which also have any/all functions.