C# LINQ Where — Complete Guide
In this tutorial, you'll learn about C# LINQ Where. We cover key concepts, practical examples, and best practices.
You have a list of items and need only those matching a condition. You write a foreach loop with an if statement, adding matching items to a new list. The LINQ Where method expresses the same filter as a declarative lambda.
Wrong
var result = new List<int>();
foreach (var item in numbers)
{
if (item > 10)
result.Add(item);
}
Output: Works. Five lines of imperative code for a simple filter.
Right
var result = numbers.Where(n => n > 10).ToList();
Output: Same list, one line. The lambda n => n > 10 is the predicate — each element is tested against it.
Where is a deferred execution method — the predicate is applied lazily as you iterate. Multiple Where calls compose into a single logical filter:
var filtered = numbers
.Where(n => n > 0)
.Where(n => n % 2 == 0)
.ToList();
// Equivalent to: numbers.Where(n => n > 0 && n % 2 == 0)
Prevention
- Use
Whereinstead offoreach+iffor filtering. - Chain multiple
Wherecalls for readability — the compiler merges them. - Use
.ToList()or.ToArray()to materialize if you need the result immediately. - Use
Wherewith index:.Where((item, index) => item > index). - Use
OfType<T>()instead ofWhere(x => x is T)when filtering by type. - Remember that
Wheredoes not modify the source — it returns a new query.
Common Mistakes with linq where
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Where is used throughout DodaTech applications for filtering — from log entries in Durga Antivirus Pro to messages in Doda Browser. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro