skip to content

A C# report finds the highest-paid employee per team with GroupBy then MaxBy; what happens on salary ties and for a team with no staff?

level: seniorimportance: should knowfreq 30%

answer

  1. strictly greater keeps the first
  2. groups are never empty
  3. null or InvalidOperationException
  4. OrderBy is a stable sort

basics

~20 s

MaxBy keeps the first element with the largest key, so ties go to whoever comes first. GroupBy groups are never empty; an empty team comes from a join, where MaxBy returns null for reference types and throws InvalidOperationException for non-nullable structs.

solid answer

~40 s

`MaxBy` replaces its candidate only when a key compares strictly greater, so among equal salaries it returns the first in source order, silently dropping the others. `OrderByDescending(e => e.Salary).First()` agrees, because `OrderBy` is a stable sort that keeps equal keys in source order. A group from `GroupBy` exists only because some employee produced its key, so `MaxBy` on a group always has an element. An empty team appears when you start from departments, through `GroupJoin` or `LeftJoin`; `MaxBy` on an empty sequence returns `null` when the element type is a reference or nullable type and throws `InvalidOperationException` ("Sequence contains no elements") for a non-nullable struct, the same as `Max()` over `decimal`. If ties matter, compute the maximum once and filter for it, or break ties explicitly with `ThenBy`.

code

csharp · 35 lines
csharp
using System;
using System.Linq;

Employee[] staff =
[
    new("Ana",  "Payroll", 5200m),
    new("Ben",  "Payroll", 6100m),
    new("Cleo", "Payroll", 6100m),
    new("Dev",  "Legal",   7000m),
];

var topPerTeam = staff
    .GroupBy(e => e.Team)
    .Select(g => g.MaxBy(e => e.Salary)!);
foreach (var e in topPerTeam)
    Console.WriteLine($"{e.Team}: {e.Name}");          // Payroll: Ben, Legal: Dev

var allTop = staff
    .GroupBy(e => e.Team)
    .Select(g =>
    {
        decimal max = g.Max(e => e.Salary);
        return (Team: g.Key, Names: g.Where(e => e.Salary == max).Select(e => e.Name));
    });
foreach (var t in allTop)
    Console.WriteLine($"{t.Team}: {string.Join(", ", t.Names)}"); // Payroll: Ben, Cleo

Employee[] nobody = [];
Console.WriteLine(nobody.MaxBy(e => e.Salary) is null);  // True: reference-type element

decimal[] noSalaries = [];
try { noSalaries.Max(); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }

record Employee(string Name, string Team, decimal Salary);

go deeper

for a junior

Know MaxBy returns the element with the biggest key, not the key itself, and that Max returns the key value.

for a middle

Explain that ties return the first element in source order and that OrderBy is stable, so the ordered form agrees with MaxBy.

for a senior

Make the tie policy explicit, know GroupBy groups are never empty, and handle the null or InvalidOperationException MaxBy gives when a join produces an empty team.

for a principal

Ensure report specifications state tie and empty-group behaviour, so code reviews check business rules rather than discovering them in production.

## The report "Highest-paid employee per team" is usually written as: ```csharp var top = staff .GroupBy(e => e.Team) .Select(g => g.MaxBy(e => e.Salary)!); ``` It reads well and runs in one pass per group. Two edge cases decide whether it is correct: **ties** and **empty teams**. ## Ties: the first one wins, silently The runtime's `MaxBy` walks the sequence and replaces its current candidate only when `comparer.Compare(nextKey, key) > 0`, a **strict** comparison. When Ben and Cleo both earn 6,100 in Payroll, Ben appears first in the list, so `MaxBy` returns Ben and Cleo never appears in the report. `MinBy` behaves the same way for the smallest key. That is deterministic for a given input order, but the input order is often an accident: the order rows came from a file, a cache or an API. A report that says "the top earner is Ben" when two people share the salary is a business bug, not a LINQ bug. Options: 1. **Return all tied employees**: compute the maximum once per group, then filter: `g.Where(e => e.Salary == maxSalary)`. 2. **Break the tie explicitly**: `g.OrderByDescending(e => e.Salary).ThenBy(e => e.Name).First()`. `MaxBy` takes one key and an `IComparer<TKey>`, so a composite tie-breaker needs either a custom comparer or the ordered form. 3. **Document that any one is acceptable** and keep `MaxBy`. `OrderByDescending(...).First()` without a `ThenBy` gives the same answer as `MaxBy`, because `OrderBy` and `OrderByDescending` are **stable**: elements with equal keys keep their source order. ## Empty teams: where they come from A `GroupBy` group is created by the first element that produces its key, so a group from `GroupBy` is **never empty**, and the `!` in the snippet above is safe. An empty team appears only when the report starts from the department list, for example with `GroupJoin(staff, ...)` to include departments that have no staff. Then the behaviour of `MaxBy` on an empty sequence matters. | Call on an empty sequence | Result | |---|---| | `MaxBy` with a class or record element | `null` | | `MaxBy` with a nullable value type element, such as `int?` | `null` | | `MaxBy` with a non-nullable struct element | throws `InvalidOperationException`: "Sequence contains no elements" | | `Max()` over `decimal` values | throws `InvalidOperationException` | | `Max()` over `decimal?` values | `null` | The implementation checks whether `default(TSource)` is `null`: if it is, an empty source returns it; otherwise it throws. The return type is annotated `TSource?`, so nullable analysis warns when you dereference the result without a check. ## Writing it robustly - Keep `GroupBy` when only staffed teams matter; the empty case cannot happen there. - When departments without staff must appear, use `GroupJoin` and handle the `null` from `MaxBy`, for example `top?.Name ?? "(no staff)"`. - When the element is a struct, guard with `Any()` or project to a nullable type before calling `MaxBy`, or the report throws on the first empty department. - Decide and test the tie policy: one arbitrary winner, a named tie-breaker, or every tied employee. - Avoid recomputing the maximum inside a filter lambda, as in `g.Where(e => e.Salary == g.Max(x => x.Salary))`, which runs `Max` once per element; compute it once per group. ## MaxBy, Max and Aggregate `Max(e => e.Salary)` returns the **key**, 6,100, not the employee; `MaxBy(e => e.Salary)` returns the **element** that holds it. Code written before `MaxBy` existed often used `Aggregate` to carry the best element so far: - `staff.Aggregate((best, e) => e.Salary > best.Salary ? e : best)` keeps the first of tied employees, like `MaxBy`; - the same lambda with `>=` keeps the **last** of them, so a one-character change flips the tie policy; - `Aggregate` without a seed throws `InvalidOperationException` ("Sequence contains no elements") on an empty sequence whatever the element type, unlike `MaxBy` over a reference type. Replacing such an `Aggregate` with `MaxBy` is a readability win, but check which comparison the old lambda used before you assume the output stays the same. ## Why interviewers ask it The happy path is one line. The follow-up, "two people share the top salary" or "a new department has nobody yet", separates a candidate who has read what `MaxBy` and `GroupBy` promise from one who has only used them on clean data.

  • Is OrderByDescending(e => e.Salary).First() slower than MaxBy because it sorts the whole team?
    In the current runtime it usually is not: the ordered sequence recognises a following `First()` and finds the top element in one pass instead of sorting. That is an implementation detail rather than a documented promise, and `MaxBy` states the intent more clearly. Both return the first of tied elements, because the sort is stable.
  • How would you report every employee who shares a team's top salary?
    Compute the maximum once per group and filter: `staff.GroupBy(e => e.Team).Select(g => { var max = g.Max(e => e.Salary); return (g.Key, g.Where(e => e.Salary == max).ToList()); })`. Computing `g.Max` inside the `Where` lambda would recompute it for every element. `MaxBy` cannot do this, since it returns one element.
  • Why does MaxBy over an empty array of a record struct throw while over an empty array of a record class it returns null?
    On an empty source `MaxBy` returns `default(TSource)` only if that default is `null`. A record class or any nullable type has a `null` default, so it is returned. A non-nullable struct has no `null` default, so instead of returning a zeroed value it throws `InvalidOperationException` with "Sequence contains no elements".

  • MaxBy returns every employee tied for the top salary
  • A group produced by GroupBy can be empty
  • MaxBy always throws on an empty sequence
  • OrderByDescending then First may return any tied employee
  • Max() over an empty decimal sequence returns zero