BP6: Any() instead of Count() > 0

When checking if an IEnumerable is empty always use enumerable.Any() instead of enumerable.Count() > 0.

How to fix things

Search for the occurence of .Count() > 0 in your code base. If it can be changed to .Any(), replace the original code by the new version.

Comments

Anonymous
Well, it depends. The best practice is more focused on a readability aspect. In LINQ implementation of Any(), the IEnumerable is enumerated in a foreach loop and if the first item matches the predicate, true is returned. Without a predicate, true is returned once the first item is reached. So from the memory and performance standpoint, there is no big difference when compared to Count() > 0 and if any, I would call it a microoptimization. Where things get more interesting is when you use Entity Framework. See the following code: // This T-SQL is generated for table.Count() SELECT COUNT(*) AS [value] FROM [table] AS [t0] vs // This T-SQL is generated for table.Any() SELECT (CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM [table] AS [t0] ) THEN 1 ELSE 0 END) AS [value] For the first case, the database engine needs to scan through whole table or index to calculate the count. For the second case, the processing ends after finding the first row.
Anonymous
Anonymous
It depends on the underlying instance of the enumerable. Each call to Any() will allocate memory, whereas Count() will not, is just a simple member access. Use benchmark.net

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play