Generics Defaults TDelegatedEqualityComparer (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the usage of TDelegatedEqualityComparer and anonymous methods for creating a custom comparer.

Code

procedure EqualityComparer;
var
  Dictionary: TDictionary<String, Cardinal>;
  Comparer: IEqualityComparer<String>;
  I: Integer;
  AString: String;
begin
  Randomize;
  { Create a new delegated comparer. You will use anonymous methods. }
  Comparer := TDelegatedEqualityComparer<String>.Create(
    { TEqualityComparison<String> }
    function(const Left, Right: String): Boolean
    begin
      { Make a case-insensitive comparison. }
      Result := CompareText(Left, Right) = 0;
    end,
    { THasher<String> }
    function(const Value: String): Integer
    begin
      { Generate a hash code. Simply return the length of the string
        as its hash code. }
      Result := Length(Value);
    end);

  { Create a new dictionary of string/cardinal. }
  Dictionary := TDictionary<String, Cardinal>.Create(Comparer);

  { Populate the dictionary with strings }
  for I := 0 to 5 do
  begin
    { Get the list from random generated numbers }
    AString := Random(5).ToString;

    { If the string is already in the dictionary, increase its count
      by one. Otherwise add it to the dictionary with the default value of one.
    }
    if Dictionary.ContainsKey(AString) then
      Dictionary[AString] := Dictionary[AString] + 1
    else
      Dictionary.Add(AString, 1);
  end;

  { Now output each string and the number of times the string was
    present in the initial memo. }
  for AString in Dictionary.Keys do
    writeln(AString + ':' + UIntToStr(Dictionary[AString]));

  { Free resources. }
  Dictionary.Free;
end;

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

Uses