IEnumerable.Any() or IEnumerable.Count() != 0

Linq makes it easy to test if a list is empty thanks to list.Count() != 0 which strongly resembles what one would have written with a List<T> (list.Count != 0).

However, the problem with this function is that it traverses the entire list to count the number of elements, whereas only one is enough. Instead, one can use list.Any() which only reads the first element of the list. So it's faster especially on large lists.

Note: The Count method checks if the type implements ICollection, in which case the value of the property ICollection.Count is used. In this case there is therefore no difference between Count() and Any().

Leave a reply