When you call Any(), it clearly communicates the code’s intention, which is to check if the collection is empty. Using Count()
== 0 for this purpose is less direct and makes the code slightly more complex. However, there are some cases where special attention should be
paid:
- if the collection is an
EntityFramework or other ORM query, calling Count() will cause executing a potentially
massive SQL query and could put a large overhead on the application database. Calling Any() will also connect to the database, but will
generate much more efficient SQL.
- if the collection is part of a LINQ query that contains
Select() statements that create objects, a large amount of memory could be
unnecessarily allocated. Calling Any() will be much more efficient because it will execute fewer iterations of the enumerable.