c# · level 3 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An iterator can go on forever, safely.
Iterators are : they do no work until someone asks for the next item, and they stop the moment nobody asks. That makes a strange thing possible: an . while (true) inside an iterator is fine, because each yield return pauses it.
The caller decides how much to take. Take(5) asks for five items, then stops asking. TakeWhile(n => n < 60) keeps asking while a test passes. Skip(2) throws the first two away. Never call Count() or ToList() on an infinite sequence: they would wait forever.
using System;
using System.Collections.Generic;
using System.Linq;
var firstFive = Squares().Take(5);
Console.WriteLine(string.Join(" ", firstFive));
var small = Squares().Skip(2).TakeWhile(n => n < 60);
Console.WriteLine(string.Join(" ", small));
IEnumerable<int> Squares()
{
int n = 1;
while (true)
{
yield return n * n;
n++;
}
} Each query calls Squares() again, so both start from 1.
guess first
An endless sequence, filtered. 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 evens = Fibonacci().Where(n => n % 2 == 0).Take(3);
Console.WriteLine(string.Join(" ", evens));
IEnumerable<int> Fibonacci()
{
int a = 1, b = 1;
while (true)
{
yield return a;
int next = a + b;
a = b;
b = next;
}
}
your turn
Your turn. Number the invoices.
On line 5, choose the first invoice number and how many invoices to make. The iterator never ends, so Take decides when to stop.
output
press run to see what happens
fix it
Page 2 of the results is empty. Can you fix it?
output
press run to see what happens
- Page 2 comes out empty. Read line 6 from left to right: what happens first?
Take(3)keeps the squares 1, 4 and 9, thenSkip(3)throws all three away.- Swap them on line 6 to
.Skip(pageSize).Take(pageSize), then run.
nailed it
you can tame sequences that never end. :D
- Iterators are lazy: they only work when asked.
TakeandTakeWhilestop asking an endless sequence.- Skip first, then take, to read one page.
new words in your collection
- lazy
- infinite sequence
This lesson isn’t saved. A free account remembers every lesson you finish.