The default sorting algorithm doesn't work like that. You need to implement Comparable
to do what you want. See Sorting Lists of sObjects:
Default Sort Order of sObjects
The List.sort
method sorts sObjects
in ascending order and compares sObjects
using an ordered sequence of steps that specify the labels or fields used. The comparison starts with the first step in the sequence and ends when two sObjects are sorted using specified labels or fields. The following is the comparison sequence used:
The label of the sObject type.
For example, an Account sObject will appear before a Contact.
The Name field, if applicable.
For example, if the list contains two accounts named A and B respectively, account A comes before account B.
Standard fields, starting with the fields that come first in alphabetical order, except for the Id and Name fields.
For example, if two accounts have the same name, the first standard field used for sorting is AccountNumber.
Custom fields, starting with the fields that come first in alphabetical order.
For example, suppose two accounts have the same name and identical standard fields, and there are two custom fields, FieldA and FieldB, the value of FieldA is used first for sorting.
Note that the label of the sObject type is applied first.
If you want to do a custom sort, you need to implement Comparable
.
Custom Sort Order of sObjects
To implement a custom sort order for sObjects
in lists, create a wrapper class for the sObject
and implement the Comparable
interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify the sort logic.
Your wrapper would look something like:
class DateSorter implements Comparable
{
final SObject record;
final Datetime value;
DateSorter(SObject record, SObjectField field)
{
this.record = record;
this.value = (Datetime)record.get(field);
}
public Integer compareTo(Object instance)
{
DateSorter that = (DateSorter)instance;
if (this.value == that.value) return 0; // extremely unlikely
return (this.value < that.value) ? 1 : -1;
}
}
Then you need to build a List<DateSorter>
, sort it, then put the ordered results in your actual List<SObject>
.
As for when to return 0
, 1
, or -1
, take a look at Comparable Interface:
Usage
The implementation of this method should return the following values:
0
if this instance and objectToCompareTo are equal
> 0
if this instance is greater than objectToCompareTo
< 0
if this instance is less than objectToCompareTo
Think about this in terms of the list index of a given element. Based on the above example, you can think about it as the relative index of this
to that
. Here, greater than
means a higher list index (later in the list), and less than
means a lower index (earlier in the list). So if you want this
before that
, return a negative index (it goes earlier), and if you want this
after that
, use a positive index (it goes later). The number doesn't have to be 1
, it can be any positive/negative Integer
.