Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

In LINQ, Don’t Use Count() When You Mean Any()

Author: Craig Stuntz

If you have a list, array, or query in a C#/LINQ application and need to check and see if the list is empty, the correct way to do this is to use the Any() extension method:

if (q.Any())
{

Similarly, you can check to see if any elements in the list meet a certain condition:

if (q.Any(i => i.IsSpecial))
{

If the query provider is something like LINQ to Entities, this will be translated into fairly efficient SQL using EXISTS.

For some reason, I see a lot of people write this code using the Count() extension method instead (maybe they don’t know about Any()?), like this:

if (q.Count() > 0)
{

This is wrong for two reasons:

Exit mobile version