Einzelnen Beitrag anzeigen

bernhard_LA

Registriert seit: 8. Jun 2009
Ort: Bayern
1.138 Beiträge
 
Delphi 11 Alexandria
 
#9

AW: Duplicate Values in TDictionary

  Alt 22. Apr 2015, 15:50
ich habe einen TCustomComparer erstellt, nur bekomme ich einen ABSTRAKTEN Fehler beim Einfügen des zweiten Datensatzes in mein TDictionary



Delphi-Quellcode:
type
  TElement = class
    name: string;
    id: integer;
    value: string;
    constructor create(aname: string; aid: integer);
  end;

  TFrequencyList = class
    data: array of integer;
    constructor create(n: integer);
  end;

  TMyComparer = class(TCustomComparer<TElement>)
    function Compare(const Left, Right: TElement): integer; override;
  end;

type
  TForm1 = class(TForm)
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private-Deklarationen }
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
  dict: TDictionary<TElement, TFrequencyList>;
  Myelement: TElement;
  FCount: TFrequencyList;
begin

  dict := TDictionary<TElement, TFrequencyList>.create( TMyComparer.create) ;

  /// code version #1
  Myelement := TElement.create('maier', 0);
  FCount := TFrequencyList.create(6);
  FCount.data[1] := 99;
  dict.Add(Myelement, FCount);

  /// code version #2
  dict.Add(TElement.create('mueller', 1), TFrequencyList.create(5));

  // Find some key -> sollten nix finden
  Myelement := TElement.create('maier', 99);
  if dict.TryGetValue(Myelement, FCount) then
  begin
    ShowMessage('Found it!: ' + IntToStr(FCount.data[1]));
  end;

  /// gibt es doch :-(
  Myelement := TElement.create('maier', 0);
  if dict.TryGetValue(Myelement, FCount) then
  begin
    ShowMessage('Found it!: ' + IntToStr(FCount.data[1]));
  end;

end;

{ TFrequencyList }

constructor TFrequencyList.create(n: integer);
begin
  setlength(data, n);
end;

{ TElement }

constructor TElement.create(aname: string; aid: integer);
begin
  self.name := aname;
  self.id := aid;
  self.value := 'dummy data';
end;

{ TMyComparer }

function TMyComparer.Compare(const Left, Right: TElement): integer;
begin
     result := Comparetext(left.name, right.name);
end;

end.
  Mit Zitat antworten Zitat