Sort a Delphi generic list with a deterministic comparer
A comparer returns a negative value when the left item comes first, zero when the items compare equal, and a positive value when the right item comes first. It does not need to return the numeric distance between the items.
For a generic Delphi list, construct an IComparer<T> with TComparer<T>.Construct and pass it to Sort. Define a tie-breaker when equal primary keys should still produce deterministic ordering. Do not subtract integers to implement comparison, because the subtraction can overflow.
Sort priority and then identity
Create a Delphi 13 console application and replace its project source with this complete program. The records have unique IDs, and priority is sorted in ascending order.
program CompareDemo;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults;
type
TItem = record
Id: Integer;
Priority: Integer;
end;
function Item(AId, APriority: Integer): TItem;
begin
Result.Id := AId;
Result.Priority := APriority;
end;
procedure Run;
var
Items: TList<TItem>;
Comparer: IComparer<TItem>;
Entry: TItem;
begin
Comparer := TComparer<TItem>.Construct(
function(const Left, Right: TItem): Integer
begin
Result := TComparer<Integer>.Default.Compare(Left.Priority, Right.Priority);
if Result = 0 then
Result := TComparer<Integer>.Default.Compare(Left.Id, Right.Id);
end);
Items := TList<TItem>.Create;
try
Items.Add(Item(2, 10));
Items.Add(Item(4, High(Integer)));
Items.Add(Item(1, 10));
Items.Add(Item(3, Low(Integer)));
Items.Sort(Comparer);
for Entry in Items do
Writeln(Entry.Id, ' ', Entry.Priority);
finally
Items.Free;
end;
end;
begin
Run;
end.
Expected output:
3 -2147483648
1 10
2 10
4 2147483647
The lowest and highest integer values deliberately exercise the overflow-prone case. The two entries with priority 10 are ordered by ID. Sort changes the list in place, so callers sharing that list observe the new order.
Preserve the comparison contract
The same pair should compare consistently for the duration of the sort. Comparing an item with itself must return zero. Reversing unequal operands should reverse the sign. If A precedes B and B precedes C, A must precede C. Mutable external state, current time or random numbers inside the comparer can violate those properties.
Use the default integer comparer rather than Left.Priority - Right.Priority. With extreme values, subtraction can wrap or raise an overflow exception depending on compiler settings. A descending comparison can swap the operands instead of negating an arbitrary comparer result, since negating the minimum integer is also problematic.
If strings are part of the key, choose case and locale behavior explicitly. A user-facing alphabetical order and a stable machine identifier order are different requirements. Ensure any later binary search uses the same ordering as the sort.
Decide what equality means
The documented list sort does not promise to preserve the relative order of equal elements. If the order among equal priorities matters, the ID tie-breaker supplies that rule. If IDs can also repeat, add another stable key or accept that those records compare equal.
For class instances rather than records, decide whether nil elements are permitted and where they belong. Dereferencing a nil object inside the comparer fails during sorting. Also distinguish list storage from object ownership. A TList<TObject> does not automatically own its instances, while an owning TObjectList<T> has a different cleanup contract.
Test an empty list, one item, duplicate primary keys, extreme numeric values and reversed inputs. Check both the resulting order and the comparer properties. Do not mutate the list or the compared keys during sorting, and avoid retaining an anonymous comparer that captures objects beyond their intended lifetime.
References
Question provenance
This article addresses How do I sort a generic list using a custom comparer? , asked by p1.e on Stack Overflow. The source question is licensed under CC BY-SA 3.0 . The explanation and examples here are newly authored for current Delphi. No answer text or code is reproduced.
Author: Herman Schoenfeld