LINQ
Prerequisites: Lambda expressions, Func, and Action
LINQ (Language Integrated Query) filters, transforms, and aggregates any collection through a uniform, chainable API — C#'s equivalent of Java's streams.
List<string> names = new() { "Ada", "Bob", "Grace", "Al" };
var longNames = names
.Where(name => name.Length > 2)
.Select(name => name.ToUpper())
.OrderBy(name => name)
.ToList();
Console.WriteLine(string.Join(", ", longNames)); // ADA, GRACE
LINQ also has an alternate query syntax, resembling SQL, equivalent to the method-chain style above:
var result = from name in names
where name.Length > 2
orderby name
select name.ToUpper();
Common mistakes
- Enumerating a LINQ query multiple times without realizing it
re-runs the whole pipeline each time (LINQ is lazy, like a
Java stream) — call
.ToList()once if the result is needed more than once.
Practice
Given List<int> nums = new() { 1, 2, 3, 4, 5, 6 };, use LINQ to
produce a list of only the even numbers, doubled.
Show solution
var result = nums
.Where(n => n % 2 == 0)
.Select(n => n * 2)
.ToList();
// { 4, 8, 12 }