Delphi XE - TObjectList Sorting

Marcoscdoni picture Marcoscdoni · Mar 21, 2014 · Viewed 8.1k times · Source

I have a list like this:

FMyScheduleList: TObjectList<TMySchedule>;

It has a property:

property ADate: TDate read FDate write FDate;

How can I sort the list by this property?

Answer

RRUZ picture RRUZ · Mar 21, 2014

You must implement a Custom IComparer function passing this implementation to the Sort method of the System.Generics.Collections.TObjectList class, you can do this using an anonymous with a method with the System.Generics.Defaults.TComparer like so .

FMyScheduleList.Sort(TComparer<TMySchedule>.Construct(
      function (const L, R: TMySchedule): integer
      begin
         if L.ADate=R.ADate then
            Result:=0
         else if L.ADate< R.ADate then
            Result:=-1
         else
            Result:=1;
      end
));

As @Stefan suggest also you can use CompareDate function which is defined in the System.DateUtils unit.

FMyScheduleList.Sort(TComparer<TMySchedule>.Construct(
      function (const L, R: TMySchedule): integer
      begin
         Result := CompareDate(L.ADate, R.ADate);
      end
));