×

c# · level 2 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.