LINQ makes it easy to check whether a sequence is non-empty using list.Count() != 0, which looks similar to the familiar List<T> property list.Count != 0.
However, Count() traverses the entire sequence to count its elements, even though you only need to know whether at least one exists. A better alternative is list.Any(), which stops after finding the first element. This makes it significantly faster on large sequences.
Note: The Count method checks whether the type implements ICollection, in which case it uses the ICollection.Count property directly. In that case, there is no performance difference between Count() and Any().
Roslyn analyzers such as Meziantou.Analyzers include rules to detect inefficient usage of Count() when Any() should be used instead. Consider enabling these analyzers in your projects to catch such issues and improve performance.
Do you have a question or a suggestion about this post? Contact me!