in the System.Linq namespace, we can now extend our IEnumerable’s to have the Any() and Count() extension methods.
I was told recently that if i want to check that a collection contains 1 or more items inside it, I should use the .Any() extension method instead of the .Count() > 0 extension method because the .Count() extension method has to iterate through all the items.
Secondly, some collections have a property (not an extension method) that is Count or Length. Would it be better to use those, instead of .Any() or .Count()?
yea / nae?
If you are starting with something that has a
.Lengthor.Count(such asICollection<T>,IList<T>,List<T>, etc) – then this will be the fastest option, since it doesn’t need to go through theGetEnumerator()/MoveNext()/Dispose()sequence required byAny()to check for a non-emptyIEnumerable<T>sequence.For just
IEnumerable<T>, thenAny()will generally be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation ofCount()does check forICollection<T>(using.Countas an optimisation) – so if your underlying data-source is directly a list/collection, there won’t be a huge difference. Don’t ask me why it doesn’t use the non-genericICollection…Of course, if you have used LINQ to filter it etc (
Whereetc), you will have an iterator-block based sequence, and so thisICollection<T>optimisation is useless.In general with
IEnumerable<T>: stick withAny();-p