score:73

Accepted answer

Use a tuple as your sort key:

myList |> Seq.sortBy (fun x -> x.Something, x.SomethingElse)

score:10

Because sortBy is defined to be stable, you can sort multiple times, using the secondary key(s) in reverse order:

myList |> Seq.sortBy (fun x -> x.SomethingElse) |> Seq.SortBy (fun x -> x.Something)

Items that compare the same for the primary key will retain the previous ordering done by the secondary key. Items that compare the same for both keys will be in the original order. This has the advantage (unlike the tuple method) that you can control whether the sort is descending for each of the keys independently.

If your sort keys are signed integers and you wish to sort, say, the secondary key in descending order, you can still use the tuple method using negation:

myList |> Seq.sortBy (fun x -> x.Something, -x.SomethingElse)

This method is arguably less clear, but may be faster than sorting twice. Be aware that it does not correctly handle the smallest value correctly because of overflow.


More Query from same tag