53 lines
1.8 KiB
Plaintext
53 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Using `.Count()` to test for emptiness works, but using `.Any()` makes the intent clearer, and the code more readable. 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.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,vbnet]
|
|
----
|
|
Private Function HasContent(Strings As IEnumerable(Of String)) As Boolean
|
|
Return Strings.Count() > 0 ' Noncompliant
|
|
End Function
|
|
|
|
Private Function HasContent2(Strings As IEnumerable(Of String)) As Boolean
|
|
Return Strings.Count() >= 1 ' Noncompliant
|
|
End Function
|
|
|
|
Private Function IsEmpty(Strings As IEnumerable(Of String)) As Boolean
|
|
Return Strings.Count() = 0 ' Noncompliant
|
|
End Function
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,vbnet]
|
|
----
|
|
Private Function HasContent(Strings As IEnumerable(Of String)) As Boolean
|
|
Return Strings.Any
|
|
End Function
|
|
|
|
Private Function HasContent2(Strings As IEnumerable(Of String)) As Boolean
|
|
Return Strings.Any
|
|
End Function
|
|
|
|
Private Function IsEmpty(Strings As IEnumerable(Of String)) As Boolean
|
|
Return Not Strings.Any
|
|
End Function
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use ".Any()" to test whether this "IEnumerable(Of XXX)" is empty or not.
|
|
|
|
endif::env-github,rspecator-view[]
|