Why should I use Any method instead of Count? [duplicate] Why should I use Any method instead of Count? [duplicate] asp.net asp.net

Why should I use Any method instead of Count? [duplicate]


Any just checks if the sequence contains at least one element, while Count needs to iterate over all elements. That's the difference. A classic scenario where Any is preferred over Count is this:

if (sec.Count() > 0)

vs

if (sec.Any())


Depending on exactly what implementation of IEnumerable<> is hiding behind the interface, Any could potentially be vastly quicker than Count. If for example there's actually LINQ-to-SQL, or some other database provider there, it could be the difference between checking a table for at least 1 record, or having to count every record in the database.

However, to my mind, the much more important reason is that using Any() expresses your INTENT better than checking for Count() > 0. It asks "are there any items?" rather than "find out how many items there are. Is that number greater than zero". Which to you is the more natural translation of "are there any items?" ?


Actually, it depends.

If your collection is in the form of an IEnumerable, the Count() method will iterate through all elements, whereas Any() won't have to. So for enumerables, Any() will have a (potentially significant) performance benefit.

In your example, however, Pets is an array, and so you would be better off using .Length rather than .Count(). In that case, there will be no significant difference of performance.