Rule Definition
Using .Count() to check if a collection or queryable contains any elements is less efficient than using .Any().
Count() enumerates the entire collection (or issues SELECT COUNT(*) in SQL)
Any() stops at the first match (or generates SELECT TOP 1 1 WHERE EXISTS(...) in SQL)
This makes Any() faster, especially with large datasets or expensive queries.
Remediation
Replace checks like if (collection.Count() > 0) with if (collection.Any()).
Exceptions & Notes
Use Count() only when you actually need the number of elements.
Any() is only for existence checks (i.e., “at least one?”).
if (collection.Count() > 0) replace by if (collection.Any())
if (collection.Count() == 0) replace by if (!collection.Any())
Violation Code Sample
if (dbContext.Users.Count() > 0) //⚠️ VIOLATION
{
Console.WriteLine("Users exist");
}
// OR
if (list.Count() > 0) { ... } //⚠️ VIOLATION
Fixed Code Sample
if (dbContext.Users.Any()) // ✓ FIXED
{
Console.WriteLine("Users exist");
}
// OR
if (list.Any()) { ... } // ✓ FIXED
Reference
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1827
Related Technologies
Technical Criterion
CWE-789 - Memory Allocation with Excessive Size Value [Variant]
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.