RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TDelegatedComparer Class

TDelegatedComparer is a generic class that delegates all comparison calls to an user-provided callback routine.

Pascal
TDelegatedComparer<T> = class(TComparer<T>);
C++
template <T>
class TDelegatedComparer : public TComparer<T>;

The primary role of TDelegatedComparer is to delegate all calls made to its Compare method to an user supplied routine.  

Use TDelegatedComparer when creating a descendant class from TComparer is not an option. Another useful feature of TDelegatedComparer is the fact that anonymous methods can be used in Delphi language to provide the required callbacks inline.  

Delphi Examples: 

 

{
This example demonstrates the usage of TDelegatedComparer and
anonymous methods in order to create a custom comparer.
The example assumes two memos and a button are present on the form.
}
procedure TForm3.Button1Click(Sender: TObject);
var
  List: TList<String>;
  Comparer: IComparer<String>;
  I: Integer;
begin
  { Create a new delegated comparer. We will use anonymous methods }
  Comparer := TDelegatedComparer<String>.Create(
    { TComparison<String> }
    function(const Left, Right: String): Integer
    begin
      { Consider the strings as numbers and return }
      { a comparison between them }
      Result := StrToInt(Left) - StrToInt(Right);
    end);

  { Create a new list of strings }
  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;

 

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