unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Generics.Collections, Generics.Defaults, StdCtrls;

type
  TForm3 = class(TForm)
    Button1: TButton;
    InMemo: TMemo;
    OutMemo: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

// BeginExample: Generics_Defaults_TDelegatedComparer
// Class: Generics.Defaults.TDelegatedComparer
// Class: Generics.Defaults.IComparer
// Method: Generics.Defaults.TDelegatedComparer.Create
// Type: Generics.Defaults.TComparison

// BeginCode
{
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;
// EndCode
// EndExample: Generics_Defaults_TDelegatedComparer

end.
