List<T> Any or Count?

Dominating picture Dominating · Apr 21, 2011 · Viewed 49.5k times · Source

When I want to do something with a list I first check it if is not null or contains no elements (not to blow a foreach) and I usually use list.Any() but what is the best option - to use list.Count > 0 , or to use list.Any()?

Answer

Ray picture Ray · Apr 21, 2011
  • Use Count if you're using a List, since it knows its size.
  • Use Length for an Array
  • 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?