Where and Filtering
Select matching elements.
What Where Does
Where is the core LINQ filtering operator. It takes a predicate — a function returning bool — and yields only the elements that satisfy it.
It lives in System.Linq and works on any IEnumerable<T>, returning a new sequence rather than mutating the source.
using System;
using System.Linq;
using System.Collections.Generic;
var nums = new List<int> { 1, 2, 3, 4, 5, 6 };
var evens = nums.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens));The Predicate Lambda
The argument to Where is a lambda n => condition. The parameter represents each element, and the body must evaluate to true or false.
Returning true keeps the element; false drops it. Any boolean expression works.
using System;
using System.Linq;
string[] words = { "apple", "fig", "banana", "kiwi" };
var shortWords = words.Where(w => w.Length <= 4);
Console.WriteLine(string.Join(", ", shortWords));All lessons in this course
- Where and Filtering
- Select and Projection
- OrderBy and Grouping
- Aggregates and ToList