Delphi XE - sorting a TObjectList

I have a list like this:

FMyScheduleList: TObjectList<TMySchedule>; 

It has the property:

 property ADate: TDate read FDate write FDate; 

How can I sort the list by this property?

+6
source share
1 answer

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

 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 )); 

Like @Stefan, you can also use the CompareDate function, which is defined in the System.DateUtils module.

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

All Articles