c# · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
keeps the items that pass your test.
The toolbox you used for Contains holds much more. LINQ is its set of methods for asking questions of a list, like “which scores passed?”. Without that using line, C# says CS1061: it cannot find the method.
Where keeps the items that pass a test. You write the test as a , a tiny function with no name: s => s >= 50 means “take s, and say whether it is at least 50”. Where runs it on every item.
Where hands back a sequence, not a list. Call to turn it into a List, or join it straight into text with string.Join.
using System;
using System.Collections.Generic;
using System.Linq;
var scores = new List<int> { 45, 82, 67, 91, 38 };
var passed = scores.Where(s => s >= 50).ToList();
Console.WriteLine(string.Join(", ", passed));
Console.WriteLine($"{passed.Count} passed"); Read => as “goes to”: each score goes to a yes or a no.
guess first
Only the long words. 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 words = new List<string> { "cat", "giraffe", "dog", "hippo" };
var longOnes = words.Where(w => w.Length > 3);
Console.WriteLine(string.Join(" ", longOnes));
Console.WriteLine(words.Count);
your turn
Your turn. Shop within your budget.
Set your budget on line 6. On line 7, write a lambda that keeps each price p that is no more than the budget. Press run.
output
press run to see what happens
fix it
The heatwave report will not run. Fix it!
output
press run to see what happens
- C# says
CS1061on line 5: aList<int>has noWhere. Where do LINQ methods live? - LINQ methods only appear when their toolbox is brought in at the top.
- Add
using System.Linq;as line 3, after the otherusinglines, then press run.
nailed it
you can filter any list. :D
using System.Linq;brings in LINQ.- A lambda like
s => s >= 50is a tiny test. .Wherekeeps what passes,.ToList()collects it.
new words in your collection
- LINQ
- lambda
- Where
- ToList
This lesson isn’t saved. A free account remembers every lesson you finish.