unit Main;

interface

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

type
  TForm3 = class(TForm)
    btCustomSort: TButton;
    InMemo: TMemo;
    OutMemo: TMemo;
    btDefaultSort: TButton;
    btOrdinalSort: TButton;
    procedure btCustomSortClick(Sender: TObject);
    procedure btDefaultSortClick(Sender: TObject);
    procedure btOrdinalSortClick(Sender: TObject);
  private
    { Private declarations }
    procedure SortMemos(const Comparer: IComparer<String>);
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

// BeginExample: Generics_Defaults_TComparer
// Class: Generics.Defaults.TComparer
// Class: Generics.Defaults.TStringComparer
// Method: Generics.Defaults.TStringComparer.Ordinal
// Method: Generics.Defaults.TComparer.Default
// Method: Generics.Defaults.TComparer.Compare

// BeginCode
{
This example demonstrates the usage of TComparer.
The example assumes two memos and three buttons are present on the form.
}

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;
begin
  { Transform the strings into ints and perform the comparison }
  Result := StrToInt(Left) - StrToInt(Right);
end;

procedure TForm3.SortMemos(const Comparer: IComparer<String>);
var
  List: TList<String>;
  I: Integer;
begin
  { Create a new list of strings with our custom comparer }
  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;

procedure TForm3.btCustomSortClick(Sender: TObject);
begin
  { Use our custom comparer }
  SortMemos(TIntStringComparer.Create());
end;

procedure TForm3.btDefaultSortClick(Sender: TObject);
begin
  { Use the default provided comparer }
  SortMemos(TComparer<String>.Default);
end;

procedure TForm3.btOrdinalSortClick(Sender: TObject);
begin
  { Use the ordinal string comparer }
  SortMemos(TStringComparer.Ordinal);
end;

// EndCode
// EndExample: Generics_Defaults_TComparer

end.
