Search⌘ K
AI Features

Common Mistakes and What to Do

Explore common LINQ mistakes such as using Count instead of Any, forgetting null checks after FirstOrDefault, and misunderstanding query evaluation. Learn how to write clearer and more efficient LINQ queries by applying best practices and avoiding typical pitfalls in C# collection handling.

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