c# · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
One call gives one answer for the whole list.
Some questions have one answer for a whole list: how much in total, how many, which is biggest? adds up the numbers a lambda picks out: spends.Sum(s => s.Amount). .Count(s => s.Kind == "food") counts only the items that pass a test.
gives the mean, and gives the biggest, with Min for the smallest. answers True if at least one item passes. On a list of plain numbers, leave the lambda out: marks.Sum().
An empty list has no biggest item, so .Max() on one stops with InvalidOperationException. Check with .Any() first.
using System;
using System.Collections.Generic;
using System.Linq;
var spends = new List<Spend>
{
new Spend("food", 12.40m),
new Spend("bus", 3.20m),
new Spend("food", 8.10m),
new Spend("cinema", 9.50m)
};
Console.WriteLine($"Total: {spends.Sum(s => s.Amount)}");
Console.WriteLine($"Food buys: {spends.Count(s => s.Kind == "food")}");
Console.WriteLine($"Biggest: {spends.Max(s => s.Amount)}");
Console.WriteLine($"Average: {spends.Average(s => s.Amount)}");
Console.WriteLine($"Any over 10? {spends.Any(s => s.Amount > 10)}");
record Spend(string Kind, decimal Amount); .Count with brackets is the LINQ method, while a list's .Count has none.
guess first
Marks out of 10. 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 marks = new List<int> { 6, 9, 4, 9, 7 };
Console.WriteLine($"{marks.Count(m => m == 9)} {marks.Max()} {marks.Average()}");
your turn
Your turn. Check a week of steps.
Set a daily goal on line 6. On line 8, use the LINQ method that finds the biggest number. Press run.
output
press run to see what happens
fix it
The auction crashes when nobody bids high. Fix it!
output
press run to see what happens
- C# stops with
InvalidOperationExceptionon line 9:Maxof nothing. Is the test on line 7 ever false? - A count is never below zero, so
>= 0always passes, even when there are no high bids. - Change line 7 to
if (high.Any()), then press run.
nailed it
one line, one answer. :D
Sum,Average,MaxandMinanswer for the whole list.CountandAnycan take a test.- Check with
.Any()before asking an empty list.
new words in your collection
- Sum
- Average
- Max
- Any
This lesson isn’t saved. A free account remembers every lesson you finish.