List<T> can do nearly anything, but a better fit is often clearer and much faster. The right question is "what do I do most: look up, add at the end, or take from the front?"
HashSet: is it in there?
A HashSet<T> holds each value once and answers "do you contain this?" almost instantly, however large it gets. A list has to look at each element. Add returns false for a duplicate, which is handy on its own.
var seen = new HashSet<string>();
foreach (string word in new[] { "to", "be", "or", "not", "to", "be" })
{
if (!seen.Add(word))
{
Console.WriteLine($"repeat: {word}");
}
}
Console.WriteLine(seen.Count);
Console.WriteLine(seen.Contains("or"));Check your prediction
repeat: to
repeat: be
4
TrueDon't rely on a set's order when you print it. If you need a set in sorted order, SortedSet<T> keeps one.
Dictionary, beyond the basics
TryGetValue avoids looking up twice and avoids the exception that a missing key throws with []. GetValueOrDefault is shorter when a default is fine, as in this count.
var counts = new Dictionary<char, int>();
foreach (char letter in "banana")
{
counts[letter] = counts.GetValueOrDefault(letter) + 1;
}
foreach (char letter in new[] { 'a', 'b', 'n', 'z' })
{
string result = counts.TryGetValue(letter, out int count) ? count.ToString() : "none";
Console.WriteLine($"{letter}: {result}");
}Check your prediction
a: 3
b: 1
n: 2
z: noneLike sets, dictionaries don't promise an order, so this example chooses the order that it prints.
Queue and Stack
A Queue<T> is first in, first out, like a line of people. A Stack<T> is last in, first out, like a pile of plates. Using them says what you mean, and taking from the front of a Queue is fast where List.RemoveAt(0) has to move every other item.
var queue = new Queue<string>();
var stack = new Stack<string>();
foreach (string job in new[] { "first", "second", "third" })
{
queue.Enqueue(job);
stack.Push(job);
}
Console.WriteLine(queue.Dequeue());
Console.WriteLine(stack.Pop());
Console.WriteLine(queue.Peek());
Console.WriteLine(stack.Count);Check your prediction
first
third
second
2Accept the least you need
A method that only loops should accept IEnumerable<T>. Then it works with lists, arrays, sets and more. Return types go the other way: be specific, such as IReadOnlyList<T>, so that callers can count and index.
Console.WriteLine(Total(new List<int> { 1, 2 }));
Console.WriteLine(Total(new[] { 3, 4 }));
Console.WriteLine(Total(new HashSet<int> { 5, 5, 6 }));
static int Total(IEnumerable<int> values)
{
int total = 0;
foreach (int value in values)
{
total += value;
}
return total;
}Check your prediction
3
7
11| You need | Use |
|---|---|
| Ordered items, by index | List<T> |
| Fast "is it there?" with no duplicates | HashSet<T> |
| Find a value by its key | Dictionary<TKey, TValue> |
| Process in arrival order | Queue<T> |
| Undo, or the most recent first | Stack<T> |
| Always take the most urgent | PriorityQueue<TItem, TPriority> |
Producing a sequence with yield
Total above accepts any IEnumerable<int>. You can also write methods that produce one, without building a list first. yield return hands a value to the caller's loop and pauses, and the method resumes when the next value is requested. A method written this way is called an iterator, and today's checkpoint practises writing them.
Predict the order of execution
The prints show who runs when. Nothing inside Count happens at the call; it happens during the loop.
IEnumerable<int> numbers = Count(2);
Console.WriteLine("Created");
foreach (int number in numbers)
{
Console.WriteLine($"Got {number}");
}
static IEnumerable<int> Count(int limit)
{
Console.WriteLine("Started");
for (int i = 1; i <= limit; i++)
{
yield return i;
}
Console.WriteLine("Finished");
}Check your prediction
Created
Started
Got 1
Got 2
FinishedBecause values are made on demand, an iterator can even be endless. The caller decides when to stop, and nothing beyond that point ever runs.
foreach (int square in Squares())
{
if (square > 20)
{
break;
}
Console.WriteLine(square);
}
static IEnumerable<int> Squares()
{
for (int n = 1; ; n++)
{
yield return n * n;
}
}Check your prediction
1
4
9
16Pipeline steps
Take a sequence, return a sequence, and you have a step that can feed another. The input can be anything you can loop over, and work happens only as the last step asks for it.
foreach (int value in Doubled(Below(new[] { 1, 5, 2, 9 }, 5)))
{
Console.WriteLine(value);
}
static IEnumerable<int> Below(IEnumerable<int> values, int limit)
{
foreach (int value in values)
{
if (value < limit)
{
yield return value;
}
}
}
static IEnumerable<int> Doubled(IEnumerable<int> values)
{
foreach (int value in values)
{
yield return value * 2;
}
}Check your prediction
2
4Fix it: Removing while you loop
This loop removes the finished tasks from a list. Run it.
var tasks = new List<string> { "done: read", "write", "done: email", "call" };
foreach (string task in tasks)
{
if (task.StartsWith("done:"))
{
tasks.Remove(task);
}
}
Console.WriteLine(string.Join(", ", tasks));Check your prediction
InvalidOperationException
Collection was modifiedA foreach walks the list by position. Removing an item shifts everything after it, so the loop would skip an item or read past the end, and the list refuses to carry on instead. Fix it so that it prints the two unfinished tasks.
Fix it
Loop over a copy and remove from the original. new List<string>(tasks) makes the copy, so removing from tasks no longer disturbs the loop:
var tasks = new List<string> { "done: read", "write", "done: email", "call" };
foreach (string task in new List<string>(tasks))
{
if (task.StartsWith("done:"))
{
tasks.Remove(task);
}
}
Console.WriteLine(string.Join(", ", tasks));write, callOn Day 3 you'll meet lambdas, which let the list do this in one call: tasks.RemoveAll(...). The same exception comes from adding to a Dictionary or HashSet while looping over it.
Your turn
Undo for a text buffer
Write a class Editor with a Text property, a method Type(string text) that appends, and a method Undo() that restores the text as it was before the latest Type. Undo with nothing to undo does nothing. Undo repeatedly must keep stepping back.
Type Hello, then , world, then !. Undo twice, printing the text each time. Undo twice more and print again, this time in square brackets, so that an empty text shows as [].
When it works, it prints:
Hello, world
Hello
[]Console.WriteLine("Start here");Hint 1: the idea
The most recent state is the first one you need back, which is exactly what a stack gives you.
Hint 2: a first step
In Type, push the current text onto a Stack<string> before changing it. In Undo, check Count first.
Show one solution
var editor = new Editor();
editor.Type("Hello");
editor.Type(", world");
editor.Type("!");
editor.Undo();
Console.WriteLine(editor.Text);
editor.Undo();
Console.WriteLine(editor.Text);
editor.Undo();
editor.Undo();
Console.WriteLine($"[{editor.Text}]");
class Editor
{
private readonly Stack<string> history = new();
public string Text { get; private set; } = "";
public void Type(string text)
{
history.Push(Text);
Text += text;
}
public void Undo()
{
if (history.Count > 0)
{
Text = history.Pop();
}
}
}Hello, world
Hello
[]A stack fits undo exactly: the last change made is the first one undone. The editor pushes the whole text before each change, so undoing is a single Pop and never has to work out what was typed. The Count > 0 check makes an extra undo do nothing, which is why the last two undos leave an empty text rather than throwing.
Completion is saved in this browser only. It does not measure mastery.