RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
IComparer Interface

IComparer is the generic interface for comparing two values of the same type.

Pascal
IComparer<T> = interface;
C++
template <T>
__interface IComparer;

The IComparer interface is implemented by classes that work as comparers for two values of the same type. Generic collections require instances of classes that implement the IComparer interface, in order to provide support for custom data types.

Note: We recommend that the TComparer class is used as base for custom comparers instead of directly implementing the IComparer interface.
 

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!