Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi XE - TObjectList Sorting

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?

like image 647
Marcoscdoni Avatar asked Mar 21 '14 15:03

Marcoscdoni


1 Answers

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
));
like image 139
RRUZ Avatar answered Oct 30 '22 07:10

RRUZ