In a recent interview I was asked what the difference between .Any() and .Length > 0 was and why I would use either when testing to see if a collection had elements.
This threw me a little as it seems a little obvious but feel I may be missing something.
I suggested that you use .Length when you simply need to know that a collection has elements and .Any() when you wish to filter the results.
Presumably .Any() takes a performance hit too as it has to do a loop / query internally.
Lengthonly exists for some collection types such asArray.Anyis an extension method that can be used with any collection that implementsIEnumerable<T>.If
Lengthis present then you can use it, otherwise useAny.Enumerable.Anydoes not loop. It fetches an iterator and checks ifMoveNextreturns true. Here is the source code from .NET Reflector.