Lesson 5 / 26
Collections and LINQ
Filter, transform and aggregate collections with LINQ.
Query a collection
LINQ (System.Linq) adds methods like Where, Select and OrderBy to any collection. They read like a pipeline and usually do not change the original list.
A small pipeline
Keep the even numbers, square them, then print. Nothing runs until ToList() or a loop forces the query to execute.
var nums = new List<int> { 1, 2, 3, 4, 5, 6 };
var result = nums.Where(n => n % 2 == 0)
.Select(n => n * n)
.ToList();
Console.WriteLine(string.Join(", ", result));
Output:
4, 16, 36
Deferred execution surprise
A LINQ query is re-evaluated each time you enumerate it. If it hits a database or is expensive, call ToList() once and reuse the list.
Quick check: Which LINQ method keeps only items matching a condition?
- Select
- OrderBy
- GroupBy
- Where
Answer
Where — `Where` filters; `Select` transforms each item into something else.