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 ...