Learn C# · lesson 31 of 61 · about 8 minutes
LINQ: Where and Select
Plan the attack: label the wave with Select, and find who falls to one hit with Where.
What you'll learn
- Write a lambda like x => x * 2
- Filter with Where
- Transform with Select and finish with ToList
Planning the attack
With the bestiary open, the hero can plan. The hero's power is typed in, and any enemy with that much HP or less falls to one hit. Instead of another loop, LINQ asks the question in one line: enemies.Where(e => bestiary[e] <= power) keeps the enemies that pass the test, and enemies.Select(e => $"{e} ({bestiary[e]})") turns each name into a label with its HP.
Queries on collections
LINQ adds query methods to every array and list.
- A lambda is a tiny unnamed method:
n => n * 2means "given n, give back n × 2" Where(n => n > 5)keeps items where the test is trueSelect(n => n * 2)turns each item into something new- Chain them, and finish with
.ToList()or.ToArray()to get a real collection
LINQ never changes the original list.
Filter and transform
List<int> scores = new() { 45, 82, 67, 91, 30 };
List<int> passes = scores.Where(s => s >= 50).ToList();
Console.WriteLine(string.Join(" ", passes));
var labels = scores.Where(s => s >= 80).Select(s => $"{s}!");
Console.WriteLine(string.Join(" ", labels));
string[] names = { "ada", "bo", "cy" };
Console.WriteLine(string.Join(", ", names.Select(n => n.ToUpper())));
Console.WriteLine(scores.Count);Output
82 67 91
82! 91!
ADA, BO, CY
5Tip
A query like scores.Where(...) is a recipe: it runs when something reads it, such as string.Join or a foreach. ToList() runs it once and keeps the answers in a real List, with a Count.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.