12

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?

Kromster
  • 7,181
  • 7
  • 63
  • 111
Marcoscdoni
  • 955
  • 2
  • 11
  • 31

1 Answers1

27

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
));
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
RRUZ
  • 134,889
  • 20
  • 356
  • 483
  • 10
    I would suggest using `DateUtils.CompareDate` which has 3 advantages: 1. you might not confuse the -1 and the 1 (happens to me all the time) 2. it actually just compares the date part and 3. shorter code in your delegate – Stefan Glienke Mar 21 '14 at 19:36
  • On a side note, I found `CompareText`, but is there a ready function for `Integer` and `Boolean`? Currently I made my own `CompareInt`. – Jerry Dodge Jun 15 '20 at 15:20
  • @JerryDodge It looks like there is one for all types of numbers called CompareValue. https://docwiki.embarcadero.com/Libraries/Sydney/en/System.Math.CompareValue – RobbZ Dec 01 '21 at 16:18