skip to content

A C# query sorts books with orderby b.Author followed by a second orderby b.Year descending, and authors come out interleaved — why, and what is the fix?

level: seniorimportance: should knowfreq 35%

answer

  1. each clause becomes its own call
  2. OrderBy starts a new primary sort
  3. a comma means ThenBy
  4. ThenBy needs an ordered source
  5. clause order is call order

basics

~20 s

Each orderby clause compiles to its own OrderBy or OrderByDescending call, and every OrderBy starts a new primary sort, so the year sort replaces the author sort. Writing one clause, orderby b.Author, b.Year descending, compiles to OrderBy then ThenByDescending.

solid answer

~40 s

The compiler translates clause by clause, in the order written: `orderby b.Author` becomes `OrderBy(b => b.Author)` and the next `orderby b.Year descending` becomes `OrderByDescending(b => b.Year)` applied to that result. `OrderByDescending` sorts the whole sequence again by year as the primary key, so authors interleave; the earlier author order survives only among books with equal years, because LINQ to Objects' sort is stable. The fix is one `orderby` with comma-separated keys, `orderby b.Author, b.Year descending`, which compiles to `OrderBy(b => b.Author).ThenByDescending(b => b.Year)`. In method syntax the same bug is `.OrderBy(…).OrderBy(…)`; `ThenBy` is declared on `IOrderedEnumerable<T>`, so it can only follow a call that returns one, such as `OrderBy`. Because clauses become calls in written order, a `where` placed before `orderby` also sorts fewer elements.

code

csharp · 25 lines
csharp
using System.Linq;

Book[] books =
[
    new("The Dispossessed", "Le Guin", 1974),
    new("Beloved", "Morrison", 1987),
    new("A Wizard of Earthsea", "Le Guin", 1968),
    new("Sula", "Morrison", 1973),
];

// Two orderby clauses: OrderBy(Author) then OrderByDescending(Year). The second sort wins.
var twoClauses = from b in books
                 orderby b.Author
                 orderby b.Year descending
                 select $"{b.Author} {b.Year}";

// One orderby with two keys: OrderBy(Author).ThenByDescending(Year).
var oneClause = from b in books
                orderby b.Author, b.Year descending
                select $"{b.Author} {b.Year}";

Console.WriteLine(string.Join(" | ", twoClauses)); // Morrison 1987 | Le Guin 1974 | Morrison 1973 | Le Guin 1968
Console.WriteLine(string.Join(" | ", oneClause));  // Le Guin 1974 | Le Guin 1968 | Morrison 1987 | Morrison 1973

record Book(string Title, string Author, int Year);

go deeper

for a junior

Recall that secondary sort keys go in the same orderby clause, separated by commas, and that ascending is the default.

for a middle

Explain how each orderby clause becomes its own OrderBy call while comma-separated keys become ThenBy, and why ThenBy requires IOrderedEnumerable<T>.

for a senior

Diagnose the interleaved output from the query text alone, explain why a stable sort hides it in small tests, and move where clauses ahead of orderby.

for a principal

Turn the finding into a review checklist item, or a custom analyzer, for repeated OrderBy calls rather than relying on test data to expose it.

## The symptom A catalogue page is meant to list books grouped by author, newest first within each author. The query reads naturally: ```csharp from b in books orderby b.Author orderby b.Year descending select b ``` The output is sorted by year alone, with authors interleaved. Nothing throws and the compiler gives no warning, so the bug usually surfaces in review or in a test with real data. ## Why: one clause, one call The compiler translates a query expression clause by clause, in the order the clauses are written, without reordering or merging them. Each `orderby` clause starts with a fresh call: | Query text | Generated calls | |---|---| | `orderby b.Author` | `OrderBy(b => b.Author)` | | `orderby b.Author orderby b.Year descending` | `OrderBy(b => b.Author).OrderByDescending(b => b.Year)` | | `orderby b.Author, b.Year descending` | `OrderBy(b => b.Author).ThenByDescending(b => b.Year)` | | `orderby b.Author descending, b.Title` | `OrderByDescending(b => b.Author).ThenBy(b => b.Title)` | `OrderBy` and `OrderByDescending` always establish a new **primary** ordering of their entire input. The second call therefore re-sorts every book by year. The first sort is not wasted entirely: `Enumerable.OrderBy` is a stable sort, so books with the same year keep the author order the first call produced. That is the only trace it leaves, and it is why small test data sometimes looks right. ## The fix 1. Put every key in **one** `orderby` clause, separated by commas, primary key first. 2. Mark each key's direction separately; `ascending` is the default and `descending` applies only to the key it follows. 3. In method syntax, write `OrderBy` or `OrderByDescending` once and `ThenBy` or `ThenByDescending` for each further key. `ThenBy` and `ThenByDescending` are extension methods on `IOrderedEnumerable<T>`, the type `OrderBy` returns, so the compiler will not let a secondary key start a chain on a plain array or list. Calling `OrderBy` twice is legal, which is why the method-syntax version of the bug compiles just as quietly as the query-syntax one. ## Clause order is execution order The same literal translation matters for `where`. Clauses become a chain of calls in written order, so: - `from b in books where b.Year > 1970 orderby b.Author select b` filters first and sorts only the survivors; - `from b in books orderby b.Author where b.Year > 1970 select b` sorts every book and then filters. Both return the same rows, but the second sorts more elements. For LINQ to Objects the compiler does not move a `where` ahead of an `orderby` for you. How a sort reads its entire source before yielding anything is covered with deferred execution; what matters here is that the query text fixes the order of the calls. ## The same bug in method syntax Method syntax offers no protection, because the chain is exactly what the compiler would have generated: ```csharp books.OrderBy(b => b.Author).OrderByDescending(b => b.Year) // re-sorts by year books.OrderBy(b => b.Author).ThenByDescending(b => b.Year) // author, then year ``` The difference between the two lines is one word, and both compile without a diagnostic. A useful reading habit is to treat every `OrderBy` or `OrderByDescending` after the first in a chain as a reset of the ordering, and every `ThenBy` as a refinement of it. If a later part of the query genuinely needs a different order, such as re-sorting the groups produced by a `group … into` continuation, a fresh `orderby` is correct; the bug is two `orderby` clauses describing one ordering. ## What to check in review - More than one `orderby` clause in one query, or `.OrderBy(…).OrderBy(…)` in a chain: almost always meant as a primary and a secondary key. - `descending` placed on the wrong key: `orderby b.Author descending, b.Year` sorts authors Z to A. - A secondary sort that needs a custom comparer, such as culture-aware string ordering: the `orderby` keyword cannot take an `IComparer<TKey>`, so that step moves to `ThenBy(keySelector, comparer)` in method syntax. - An `orderby` before a `group … by`: grouping keeps groups in first-seen key order, so a sort meant for the groups often belongs after the continuation instead. The habit that prevents the bug is simple: one `orderby`, keys in priority order, commas between them.

  • Why does the two-orderby bug sometimes pass tests in C#?
    `Enumerable.OrderBy` is stable, so books that share a year keep the author order from the first sort, and fixtures where many books share a year look partly right. When the year order also happens to keep each author's books together, the output looks fully correct, while real data interleaves.
  • Can a C# orderby clause use a custom comparer, such as a culture-aware string comparison?
    No. The `orderby` keyword always uses the key type's default comparer. Write that step in method syntax with the overload that takes an `IComparer<TKey>`, for example `OrderBy(b => b.Author, StringComparer.Create(culture, ignoreCase: true))`, followed by `ThenBy` for the remaining keys.

  • The compiler merges consecutive orderby clauses into one multi-key sort.
  • A second OrderBy call refines the first instead of replacing it.
  • descending in orderby a, b descending applies to both keys.
  • ThenBy can start an ordering directly on a List<T>.
  • The compiler moves where clauses ahead of orderby automatically.