Common Mistakes and What to Do

Learn basic mistakes when working with LINQ and how to fix them.

Count instead of Any

We should always prefer Any over Count to check if a collection has any elements, or at least one element, that meets a condition.

Let’s write movies.Any() instead of movies.Count() > 0.

The 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 Any

We can use a condition with Any directly, instead of filtering first with Where to then use Any.

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 FirstOrDefault, Count, or any other method that receives a filter condition. We can use the filter condition directly instead of relying on the Where method.

FirstOrDefault without null checking

Let’s always check if we have a result when working with FirstOrDefault, LastOrDefault, and SingleOrDefault.

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 null reference—

Get hands-on with 1000+ tech skills courses.