RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TComparer.Compare Method

Compare is a generic method used to compare two values.

Pascal
function Compare(const Left: T; const Right: T): Integer; virtual; abstract;
C++
virtual __fastcall int Compare(const T Left, const T Right) = 0;

Use the Compare method to compare two values of the same type. Any class that descends from TComparer is expected to implement the Compare method.  

The return value of Compare must be in the following ranges.

Return value  
Description  
Result is less than zero (<0)  
Left is less than Right.  
Result is equal to zero (=0)  
Left is equal to Right.  
Result is greater than zero (>0)  
Left is greater than Right.  

 

Delphi Examples: 

{
This example demonstrates the usage of TComparer.
The example assumes two memos and three buttons are present on the form.
}

type
  { Declare a new custom comparer }
  TIntStringComparer = class(TComparer<String>)
  public
    function Compare(const Left, Right: String): Integer; override;
  end;

{ TIntStringComparer }

function TIntStringComparer.Compare(const Left, Right: String): Integer;
begin
  { Transform the strings into ints and perform the comparison }
  Result := StrToInt(Left) - StrToInt(Right);
end;

procedure TForm3.SortMemos(const Comparer: IComparer<String>);
var
  List: TList<String>;
  I: Integer;
begin
  { Create a new list of strings with our custom comparer }
  List := TList<String>.Create(Comparer);

  { Populate the list with numbers in the memo }
  for I := 0 to InMemo.Lines.Count - 1 do
    List.Add(InMemo.Lines[I]);

  { Sort the list }
  List.Sort();

  { Copy the list with numbers to the memo }
  OutMemo.Clear;

  for I := 0 to List.Count - 1 do
    OutMemo.Lines.Add(List[I]);

  { Free resources }
  List.Free();
end;

procedure TForm3.btCustomSortClick(Sender: TObject);
begin
  { Use our custom comparer }
  SortMemos(TIntStringComparer.Create());
end;

procedure TForm3.btDefaultSortClick(Sender: TObject);
begin
  { Use the default provided comparer }
  SortMemos(TComparer<String>.Default);
end;

procedure TForm3.btOrdinalSortClick(Sender: TObject);
begin
  { Use the ordinal string comparer }
  SortMemos(TStringComparer.Ordinal);
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!