I'm guessing the interviewer may have meant to ask about checking Any()
versus Count() > 0
(as opposed to Length > 0
).
Basically, here's the deal.
Any()
will effectively try to determine if a collection has any members by enumerating over a single item. (There is an overload to check for a given criterion using a Func<T, bool>
, but I'm guessing the interviewer was referring to the version of Any()
that takes no arguments.) This makes it O(1).
Count()
will check for a Length
or Count
property (from a T[]
or an ICollection
or ICollection<T>
) first. This would generally be O(1). If that isn't available, however, it will count the items in a collection by enumerating over the entire thing. This would be O(n).
A Count
or Length
property, if available, would most likely be O(1) just like Any()
, and would probably perform better as it would require no enumerating at all. But the Count()
extension method does not ensure this. Therefore it is sometimes O(1), sometimes O(n).
Presumably, if you're dealing with a nondescript IEnumerable<T>
and you don't know whether it implements ICollection<T>
or not, you are much better off using Any()
than Count() > 0
if your intention is simply to ensure the collection is not empty.