c# · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
turns every item into something new.
Select runs a lambda on each item and hands back a sequence of the answers. menu.Select(d => d.Name.ToUpper()) turns every dish into its name in capitals. numbers.Select(n => n * 2) doubles every number.
Each LINQ method hands back a sequence, so you can call another straight after it. This is : .Where(...) picks the cheap dishes, then .Select(...) turns those into text. Read a chain from left to right, like a production line.
Neither method changes the original list. They build new sequences and leave menu as it was.
using System;
using System.Collections.Generic;
using System.Linq;
var menu = new List<Dish> { new Dish("soup", 4.50m), new Dish("pie", 6.00m), new Dish("salad", 5.25m) };
var shouts = menu.Select(d => d.Name.ToUpper());
Console.WriteLine(string.Join(", ", shouts));
var cheap = menu.Where(d => d.Price < 6).Select(d => $"{d.Name} {d.Price}");
Console.WriteLine(string.Join(" | ", cheap));
record Dish(string Name, decimal Price); Records and LINQ work well together: each lambda reads a record's properties.
guess first
Filter, then reshape. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
using System.Linq;
var nums = new List<int> { 1, 2, 3, 4, 5, 6 };
var result = nums.Where(n => n % 2 == 0).Select(n => n * 10);
Console.WriteLine(string.Join(",", result));
your turn
Your turn. Describe the grown-ups.
Finish the lambda on line 6 so each adult becomes text like Ada is 36. Press run.
output
press run to see what happens
fix it
The big orders came out as True and False. Fix it!
output
press run to see what happens
- The output shows True and False. What did
.Selectturn each order into? Selectturns every item into the lambda's answer. To keep only some items, use the method that filters.- Change
SelecttoWhereon line 6, then press run.
nailed it
you can reshape a whole list. :D
.Selectturns each item into something new.- Chain
.Whereand.Select, reading left to right. - The original list never changes.
new words in your collection
- Select
- chaining
This lesson isn’t saved. A free account remembers every lesson you finish.