Common Mistakes and What to Do
Count instead of
We should always prefer
Count to check if a collection has any elements, or at least one element, that meets a condition.
movies.Any() instead of
movies.Count() > 0.
Any method returns when it finds at least one element that meets the condition, but the
Count method evaluates the entire query.
Where followed by
We can use a condition with
Any directly, instead of filtering first with
Where to then use
Let’s write the following line:
movies.Any(movie => movie.Rating == 5)
We’ll use the above line instead of this one below:
movies.Where(movie => movie.Rating == 5).Any()
The same applies to the
Where method followed by
Count, or any other method that receives a filter condition. We can use the filter condition directly instead of relying on the
Let’s always check if we have a result when working with
When any of the three above methods don’t find results, they return the default value of the collection type.
For objects, the default value would be a
null reference. And you know what happens when we access a property or method on a