skip to content

Why can `List<T>.Sort` in C# reorder entities that compare equal, and how do you sort them by layer while keeping placement order?

level: middleimportance: should knowfreq 40%

answer

  1. the same engine as Array.Sort
  2. introspective sort partitions
  3. small inputs hide the problem
  4. OrderBy or an index tiebreaker

basics

~20 s

List<T>.Sort runs the same introspective sort as Array.Sort, which is unstable: elements that compare equal may come out in any relative order. Keep placement order with Enumerable.OrderBy, which is stable, or add the original index as a tiebreaker.

solid answer

~40 s

Every `List<T>.Sort` overload, whether it takes nothing, an `IComparer<T>` or a `Comparison<T>`, sorts the backing array in place with the runtime's introspective sort: quicksort partitioning, a heapsort fallback when recursion gets too deep, and insertion sort for small partitions. Partitioning swaps distant elements, so two entities on the same layer can swap places. In the current implementation a list of 4 to 16 elements goes straight to insertion sort and happens to look stable, so small tests pass, although three elements can already swap. To keep placement order, use `placed.OrderBy(e => e.Layer).ToList()`, which is stable but allocates a new list, or keep `Sort` and compare a placement index when the layers tie. Exceptions thrown by your comparison come back wrapped in `InvalidOperationException`.

code

csharp · 19 lines
csharp
var placed = new List<Entity>();
for (int i = 0; i < 40; i++) placed.Add(new Entity($"e{i:00}", Layer: i % 2));

var unstable = new List<Entity>(placed);
unstable.Sort((a, b) => a.Layer.CompareTo(b.Layer));
Console.WriteLine(string.Join(" ", unstable.Take(6).Select(e => e.Name)));

var stable = placed.OrderBy(e => e.Layer).ToList();
Console.WriteLine(string.Join(" ", stable.Take(6).Select(e => e.Name)));

var indexed = placed.Select((e, i) => (Entity: e, Index: i)).ToList();
indexed.Sort((a, b) =>
{
    int byLayer = a.Entity.Layer.CompareTo(b.Entity.Layer);
    return byLayer != 0 ? byLayer : a.Index.CompareTo(b.Index);
});
Console.WriteLine(string.Join(" ", indexed.Take(6).Select(x => x.Entity.Name)));

record Entity(string Name, int Layer);

go deeper

for a junior

Know the Sort overloads and how to pass a Comparison<T> lambda such as (a, b) => a.Layer.CompareTo(b.Layer). Know that Sort changes the list itself.

for a middle

Explain that List<T>.Sort is Array.Sort's introspective sort and unstable, that OrderBy is stable, and how a tiebreaker turns any sort into a deterministic one.

for a senior

Diagnose flickering draw order or nondeterministic output as instability, explain why small tests miss it, and choose between OrderBy's allocation and an in-place tiebreaker for the hot path.

for a principal

Where output order is observable (rendering, saved files, diffs), ask for a total order in every comparison so results do not depend on which algorithm a runtime happens to use.

## The Sort overloads `List<T>` has four `Sort` overloads: `Sort()`, `Sort(IComparer<T>?)`, `Sort(Comparison<T>)` and `Sort(int index, int count, IComparer<T>?)`. They all sort **in place**, rearranging the list's own backing array, and the reference source routes them to the same engine as `Array.Sort`: the generic `ArraySortHelper<T>`. With no comparer, elements are compared through `Comparer<T>.Default`, which needs `T` to implement `IComparable<T>` or `IComparable`. The choice between the overloads is mostly about reuse. A `Comparison<T>` lambda is the quickest to write at the call site; an `IComparer<T>` is an object you can store, share and pass to other APIs such as `Array.Sort`, `SortedSet<T>` or `BinarySearch`, and `Comparer<T>.Create(comparison)` turns the first into the second. The range overload sorts only part of the list, for example just the entities appended by the last load, and leaves the rest where it is. Every overload increments the list's version, so a `foreach` that is still walking the list throws `InvalidOperationException` on its next step. ## Why the sort is unstable A **stable** sort keeps elements that compare equal in their original relative order; an **unstable** sort makes no such promise. `ArraySortHelper<T>` runs an **introspective sort**: 1. **Quicksort partitioning** picks a pivot and swaps elements across it, often moving an element past others that are equal to it. 2. A **heapsort** fallback takes over when the recursion depth passes a limit, protecting the worst case. 3. **Small partitions** of 16 elements or fewer (`Array.IntrosortSizeThreshold` is 16 in the source) skip partitioning: two or three elements are ordered with compare-and-swap steps, and 4 to 16 elements go through insertion sort. Step 1 is what breaks placement order. In the level editor, 40 entities alternating between layers 0 and 1 and sorted by layer came out as `e00 e22 e28 e20 e38 e18` for layer 0, not `e00 e02 e04 …`. If entities on one layer are drawn in list order, that is visible as sprites swapping in front of each other after every re-sort. ## The small-list trap Insertion sort is stable, so a list of 4 to 16 elements goes through only that step and keeps its equal elements in order; in a test run, ten entities alternating between two layers came back in placement order. A unit test with a handful of entities therefore passes, and the bug appears only on real levels. The rule is not even tidy: the three-element case uses three compare-and-swap steps, and sorting `(1, a), (1, b), (0, c)` by layer returned `c b a`. All of this is an implementation detail of the current runtime, not a guarantee in either direction: never rely on small lists staying in order, and test sorting with inputs larger than the threshold. ## Ways to keep placement order | Approach | Stable | Allocates | Changes the list in place | |---|---|---|---| | `list.Sort(comparison)` | no | no | yes | | `list.OrderBy(e => e.Layer).ToList()` | yes | a new list plus buffers | no, you get a new list | | `list.Sort` with a placement-index tiebreaker | yes, by construction | only if you add the index | yes | - **`Enumerable.OrderBy`** is a stable sort: the LINQ source breaks ties by comparing original positions (`index1 - index2`, commented "ensure stability of sort"). Chain `ThenBy` for further keys. It returns a new sequence, so assign the result back. - **A tiebreaker** makes equal elements unequal: give each entity a placement sequence number, or pair entities with their index, and compare it when the layers match. The comparison then defines a total order and any sort algorithm returns the same result. ## Comparison mistakes worth knowing - **Exceptions are wrapped.** If the comparison throws, say a `NullReferenceException` on a null entity, `Sort` rethrows it as **`InvalidOperationException`** ("Failed to compare two elements in the array.") with the original as `InnerException`. - **No ordering at all.** `Sort()` on a type with no `IComparable` implementation fails the same way, with an inner `ArgumentException` ("At least one object must implement IComparable."). - **Descending order** is a reversed comparison, `(a, b) => b.Layer.CompareTo(a.Layer)`, not a call to `Reverse()` afterwards, which would also reverse the tie order. - **Subtraction comparers** like `(a, b) => a.Layer - b.Layer` overflow for large values of opposite sign; `CompareTo` does not. - **Inconsistent comparisons** (one that says a < b and b < a) can produce a scrambled order, and when the sort's index arithmetic notices, an `ArgumentException` about the comparer.

  • Why did `Sort` throw `InvalidOperationException` when the real bug was a null element?
    `ArraySortHelper<T>` wraps any exception escaping the comparison in `InvalidOperationException` with the message "Failed to compare two elements in the array." and keeps the original as `InnerException`. Look at the inner exception: a `NullReferenceException` means the comparison dereferenced a null element; an `ArgumentException` saying an object must implement `IComparable` means no comparer was supplied for a type without one.
  • When is `OrderBy(...).ToList()` the wrong fix for an unstable `List<T>.Sort`?
    When the sort runs every frame or on a hot path. `OrderBy` buffers the source, builds a key array and returns a new list, so each call allocates. A tiebreaker on a sequence number kept in the entity lets `List<T>.Sort` stay in place and allocation-free while producing the same order.

  • List<T>.Sort is a merge sort, so equal elements keep their order.
  • My test with ten items passed, so the sort is stable.
  • OrderBy and List<T>.Sort give the same order for equal keys.
  • Calling Reverse after an ascending sort gives a proper descending sort.
  • a.Layer - b.Layer is a safe comparison for any int values.