List<T> Any or Count? [duplicate]
Solution 1:
- Use
Count
if you're using aList
, since it knows its size. - Use
Length
for anArray
- If you just have an
IEnumerable
I would use.Any()
over.Count()
as it will be faster since it stops after checking one item.
Also check out this question: Which method performs better: .Any() vs .Count() > 0?
Solution 2:
I use list.Count > 0
just because it doesn't depend on the LINQ methods and so works on C# 2.0.
I personally avoid LINQ like the plague (because of its slow speed), and there's no reason to use extension methods here at all anyway.
However, a better solution would probably be to make your own version of Any
that would take in a null
reference, and return true if it's a collection with elements. That would save you the null check.
Solution 3:
.Any()
is generally better to use than .Count() > 0
. The reason for this is that if the items you are iterating over is not an ICollection
then it will have to iterate the whole list to get the count.
But if the items is an ICollection
(which a List<T>
is) then it is just as fast or in some cases faster to use Count()
(Any()
iterates once regardless of underlying type in MS .Net but Mono tries to optimize this to Count > 0
when the underlying items is an ICollection
)
A great tool is Reflector, the .Net source code and the Mono source code which allows you to see how things are implemented.