C List Sort by x then y
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sorting by x and then by y is a standard multi-key sort: compare x first, and only if two items have the same x, compare y. In C#, you can do this either in place with List<T>.Sort or by creating a new ordered sequence with LINQ.
Sort In Place With List<T>.Sort
If you already have a List<T> and want to reorder that list directly, use Sort with a comparison lambda.
The comparison logic reads naturally:
- Compare
X - If
Xdiffers, return that result - Otherwise compare
Y
That is the direct answer to "sort by x then y."
Use LINQ When You Want a New Sequence
If you prefer a more declarative style, or you do not want to mutate the original list, use OrderBy and ThenBy.
This is often the most readable version, especially when the sort rules get longer or when you are already writing a LINQ pipeline.
Choose Between Sort and LINQ
The two approaches solve slightly different problems:
- '
List<T>.Sortmutates the existing list' - '
OrderBy(...).ThenBy(...)creates a new ordered sequence'
Use Sort when you care about avoiding an extra list allocation or you explicitly want the original list reordered. Use LINQ when clarity matters more or when immutability is helpful.
Sort Descending on the Secondary Key
You can vary the secondary rule easily. For example, sort by X ascending and Y descending:
The same pattern scales to three or more keys with additional ThenBy or ThenByDescending calls.
Use a Reusable Comparer When the Rule Matters
If the same sort rule appears in multiple places, extract it into an IComparer<T> instead of repeating lambdas everywhere.
That is useful when the rule is part of the domain rather than a one-off call-site detail.
Common Pitfalls
- Returning only
a.X.CompareTo(b.X)sorts byxalone and ignoresyties. - Assuming
OrderBymodifies the original list is incorrect; it returns a new sequence. - Mixing ascending and descending requirements without being explicit can produce subtle ordering bugs.
- Writing complex comparison logic inline everywhere makes code harder to maintain. Extract a comparer if the rule is reused.
Unit tests are especially helpful when multi-key sort rules become part of business logic.
Summary
- To sort by
xtheny, comparexfirst and useyonly as the tie-breaker. - Use
List<T>.Sortfor in-place sorting. - Use
OrderBy(...).ThenBy(...)when you want a new sorted sequence. - The same multi-key pattern extends naturally to additional sort fields.

