I want to sort TObjectList<T> using my own comparer function the comparer function code shown below.
I want from my ObjectList to be able to sort in two direction ascending and descending in order to accomplish this I use SysUtil.CompareText which has two parameters S1 and S2 and to sort in descending way I just opposite the sign of the CompareText result. I don't know if exist another solution everything is fine if s1 greater than S2 or vice versa however if s1 = s2 in the normal case there is no reindex in the list because all elements in the column are identical but the Opposite happened TObjectList sorted the list as if s1 > s2 or s1 < s2..
My question is how implement a comparer that supports equality and differences?
TPerson = class
private
FName: string;
FId: string;
public
property Name: string read FName write FName;
property ID: string read FID write FID;
end;
TPersons = class(TObjectList<TPerson>)
public
constructor Create();
procedure Sort(Direction: string); reintroduce;
end;
procedure TForm4.Button1Click(Sender: TObject);
var
PersonsList: TPersons;
I: Integer;
begin
PersonsList := TPersons.Create;
PersonsList.Sort('Ascending');
for I := 0 to PersonsList.Count - 1 do
ShowMessage(PersonsList[i].Name);
end;
{ TPersons }
constructor TPersons.Create;
var
Person: TPerson;
begin
Person := TPerson.Create;
Person.Name := 'fateh';
Person.ID := '1';
Self.Add(Person);
Person := TPerson.Create;
Person.Name := 'mohamed';
Person.ID := '1';
Self.Add(Person);
Person := TPerson.Create;
Person.Name := 'oussama';
Person.ID := '1';
Self.Add(Person);
// all ids are identical
end;
procedure TPersons.Sort(Direction: string);
var
Comparer : IComparer<TPerson>;
Comparison : TComparison<TPerson>;
begin
if Direction = 'Ascending' then
Comparison := function(const Person1, Person2 : TPerson): Integer
begin
result := CompareText(Person1.ID, Person2.ID);
end;
if Direction = 'Descending' then
Comparison := function(const Person1, Person2 : TPerson): Integer
begin
result := - CompareText(Person1.ID, Person2.ID);
end;
Comparer := TComparer<TPerson>.Construct(Comparison);
inherited Sort(Comparer);
end;