Lesson 3: Filtering & Projection with LINQ
Filtering and projection are two of the most important LINQ patterns. Filtering selects the subset of data you need, and projection shapes each item into the form you want.
Filter with Where
Where filters a sequence by a condition. Each item is passed to a lambda function that returns true or false.
var users = new[]
{
new { Name = "Ava", Age = 23 },
new { Name = "Leo", Age = 31 },
new { Name = "Mia", Age = 19 }
};
var adults = users.Where(user => user.Age >= 21);
Shape Data with Select
Select projects each item into a new form, such as an anonymous type or a primitive value.
var names = users.Select(user => user.Name);
var summaries = users.Select(user => new { user.Name, user.Age });
Use SelectMany for Nested Collections
SelectMany flattens nested collections into a single sequence.
var orders = new[]
{
new { OrderId = 101, Items = new[] { "Pen", "Notebook" } },
new { OrderId = 102, Items = new[] { "Mouse", "Keyboard" } }
};
var allItems = orders.SelectMany(order => order.Items);
Distinct, Take, and Skip
LINQ also includes operators for deduplication and paging:
Distinct()removes duplicates.Take(n)returns the firstnitems.Skip(n)skips the firstnitems.
🧠 Quick Check — Lesson 3
Which operator flattens nested collections into one sequence?
Projection Example
Projection is useful when you only need specific fields or when you want to transform data for UI or reporting.
var emailList = users
.Where(user => user.Age >= 21)
.Select(user => $"{user.Name.ToLower()}@example.com");
Lesson Summary
Where filters items based on a condition.
Select projects each item into a new shape.
SelectMany flattens nested sequences into one stream.
Distinct, Take, and Skip are handy for unique values and paging.