Generics Defaults TDelegatedComparer (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of TDelegatedComparer and anonymous methods in order to create a custom comparer.

Code

procedure Sort;
var
  List: TList<String>;
  Comparer: IComparer<String>;
  I: Integer;
begin
  Randomize;
  { Create a new delegated comparer. You 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 random numbers. }
  for I := 0 to 5 do
    List.Add(Random(5).ToString);

  { Sort the list }
  List.Sort;


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

  { Free resources }
  List.Free;
end;

begin
  { Call the procedure defined above }
  Sort;
  readln;
end.

Uses

Personal tools
Assistance