c# · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A LINQ query is a recipe, not a meal.
var cheap = prices.Where(p => p < 5); does not filter anything yet. It stores a recipe. The work happens later, each time something walks through cheap: a foreach, Count() or string.Join. This is .
So a query sees the data as it is when it runs, not when it was written. Add an item to the list afterwards and the next walk includes it. Walk the query twice and the work is done twice. First stops walking as soon as it has an answer.
When you want the answer fixed, call ToList(). It runs the recipe once and keeps a that later changes do not touch.
using System;
using System.Collections.Generic;
using System.Linq;
var prices = new List<int> { 3, 8, 2 };
var cheap = prices.Where(p => p < 5);
var cheapNow = prices.Where(p => p < 5).ToList();
prices.Add(1);
Console.WriteLine(string.Join(", ", cheap));
Console.WriteLine(string.Join(", ", cheapNow)); string.Join(", ", items) glues every item into one line, with , between them.
guess first
Who gets shouted? 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 names = new List<string> { "ana", "ben", "cy" };
var loud = names.Select(name =>
{
Console.WriteLine($"shouting {name}");
return name.ToUpper();
});
Console.WriteLine("ready");
Console.WriteLine(loud.First());
your turn
Your turn. Keep the results.
Choose a pass mark in the first gap on line 6. Then fill the second gap so the results are a snapshot that survives scores.Clear() on line 7.
output
press run to see what happens
fix it
Tidying the basket crashes. Can you fix it?
output
press run to see what happens
- It crashes with
InvalidOperationException: the collection was modified. Which list is the loop walking? - The live query walks
basketwhileRemovechangesbasketunderneath it. - Add
.ToList()after theWhere(...)on line 6, so the loop walks a snapshot, then run.
nailed it
your queries run exactly when you mean. :D
- A LINQ query is a recipe that runs when walked.
Firststops walking as soon as it can.ToList()runs it once and keeps a snapshot.
new words in your collection
- deferred execution
- snapshot
This lesson isn’t saved. A free account remembers every lesson you finish.