Generics Defaults TComparer (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of TComparer. The example requires that two memos and three buttons are present on the form. The content of InMemo is sorted and displayed in OutMemo. Three TComparer instances are used:

  • A default one (Default)
  • A String comparer
  • A user-defined integer comparer

Code

uses
  System.Generics.Defaults, System.Generics.Collections, System.AnsiStrings;

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;
var
  LeftTerm, RightTerm: Integer;
begin
  { Transform the strings into integers and perform the comparison. }
  try
    LeftTerm := StrToInt(Left);
    RightTerm := StrToInt(Right);
    Result := LeftTerm - RightTerm;
  except
    on E: Exception do
    begin
      writeln('Not a number!');
      Result := CompareStr(Left, Right);
    end;
  end;
end;

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

  writeln('Initial list:');
  { Populate the list with random numbers. }
  for I := 0 to 5 do
  begin
    List.Add(IntToStr(Random(5)));
    writeln(List[I]);
  end;
  { Sort the list. }
  List.Sort;

  writeln('Sorted list:');
  for I := 0 to List.Count - 1 do
    writeln(List[I]);

  { Free resources. }
  List.Free;
end;



var
  Cmp: TIntStringComparer;
begin
  { Use our custom comparer. }
  Cmp := TIntStringComparer.Create;
  SortMemos(Cmp);
  readln;
end.

Uses