Skip to content

Come Back Later

The Course
•
30 min study

Return to this page after two or three days, and again after about a week. Start each time with a blank editor. These challenges are extra review, outside Day 7's time estimate.

Retrieve: without looking, write a generic Result<T> with Ok and Fail, and a method that uses it. Write a query that groups a list and totals each group. Explain to an imaginary colleague why ToList sometimes matters.

Debug: predict the output of each program before you run it. Each one contains a classic mistake from this week. Explain the cause, then fix it.

Debug 1: the query that changed its mind C#
var numbers = new List<int> { 1, 2, 3 };
var big = numbers.Where(n => n > 1);
numbers.Clear();
Console.WriteLine(big.Count());
Check your prediction
Text
0
Debug 2: the method that was not overridden C#
Animal pet = new Dog();
Console.WriteLine(pet.Sound());

class Animal
{
    public string Sound() => "generic";
}

class Dog : Animal
{
    public new string Sound() => "woof";
}
Check your prediction
Text
generic
Debug 3: the rewind you forgot C#
using var stream = new MemoryStream();
using var writer = new StreamWriter(stream);
writer.Write("hello");
writer.Flush();

using var reader = new StreamReader(stream);
Console.WriteLine($"[{reader.ReadToEnd()}]");
Check your prediction
Text
[]
Debug 4: equal records, different lists C#
var first = new Tagged("a", new List<string> { "x" });
var second = new Tagged("a", new List<string> { "x" });
Console.WriteLine(first == second);
Console.WriteLine(first.Tags.SequenceEqual(second.Tags));

record Tagged(string Name, List<string> Tags);
Check your prediction
Text
False
True

Transfer: build the method below from its description alone. Choose test cases that would catch a word counted twice because of its case, the wrong number of results when there are fewer words than count, and ties in the wrong order.

Your turn

Exercise

Top words

Write TopWords(IEnumerable<string> lines, int count), returning the count most common words across all lines, as (string Word, int Uses) tuples. Compare words case-insensitively by lowercasing them, ignore extra spaces, sort by uses, highest first, then by word. Return fewer if there aren't enough, and nothing for empty input. Print Review checks passed if your checks pass.

When every check passes, it prints:

Text
Review checks passed
Your workspace C#
Console.WriteLine("Review checks passed");
Hint 1: the idea

Lines become words with SelectMany. After that, it's a group, a count, two sort keys and a Take.

Hint 2: a first step

Write the query up to GroupBy, and print the keys. Add a check for the tie first, so that you see it fail.

Show one solution
C#
int failures = 0;

var top = TopWords(new[] { "the cat  The dog", "a dog" }, 2).ToList();
Check(top.Count == 2, "returns the requested count");
Check(top[0] == ("dog", 2) && top[1] == ("the", 2), "ties sort by word");
Check(!TopWords(Array.Empty<string>(), 3).Any(), "empty input");
Check(TopWords(new[] { "one" }, 5).Count() == 1, "fewer than requested");

if (failures == 0)
{
    Console.WriteLine("Review checks passed");
}

void Check(bool passed, string name)
{
    if (!passed)
    {
        Console.WriteLine($"FAILED: {name}");
        failures++;
    }
}

static IEnumerable<(string Word, int Uses)> TopWords(IEnumerable<string> lines, int count)
{
    return lines
        .SelectMany(line => line.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries))
        .GroupBy(word => word)
        .Select(group => (Word: group.Key, Uses: group.Count()))
        .OrderByDescending(row => row.Uses)
        .ThenBy(row => row.Word)
        .Take(count);
}
Text
Review checks passed

SelectMany flattens every line's words into one sequence, and lowercasing first makes The and the the same word. ThenBy(row => row.Word) makes ties come out in a fixed order, which is what lets a check compare exact positions. Returning the query without ToList() keeps it lazy; the checks call ToList() or Count() when they need results.

Decide what to revisit

If deferred execution still surprises you, go back to Day 3 and write a query with a Console.WriteLine inside its lambda. If using and streams felt shaky, rewrite the Day 5 checkpoint. If you could only finish the tracker's extension by copying, repeat the expense ledger from a blank editor.

When you're ready, Advanced C# goes on to precise value types, asynchronous code and channels, and builds a concurrent job runner. Debug 2 above is the hiding mistake from Day 1's "Fix it" step, this time written with new on purpose: new hides a method and doesn't replace it, which is why the override you learned on Day 1 matters.

Was this article helpful?

Your response is saved on this device.