0

how to handle the error of duplicate value in the list. Values are fed into the input and entered into the list. If there is a duplicate then the value is renamed. eg:

procedure TForm2.Button1Click(Sender: TObject);
var
 CollectionNameTable : TDictionary<string, Integer>;
begin
  CollectionNameTable := TDictionary<string, Integer>.Create();
   try
     CollectionNameTable.Add('One', 1);
     CollectionNameTable.Add('TWO', 2);
     CollectionNameTable.Add('TWO', 3);
     CollectionNameTable.Add('FOUR', 4);
      except on E: EStringListError do
       begin
          ShowMessage( 'Дубликат!!!');
          CollectionNameTable.Add('DOUBLE_FREE', 3);
       end;

   end;

    CollectionNameTable.Clear;
    CollectionNameTable.Free;

end;
  • Call `ContainsKey` before attempting to add, and handle the error at that point. You should not wait for an exception to be raised. A better dictionary class (e.g. spring4d) offers the `TryAdd` pattern which is more efficient. – David Heffernan Dec 18 '20 at 12:27
  • 1
    Are you looking for [`AddOrSetValue`](http://docwiki.embarcadero.com/Libraries/Sydney/en/System.Generics.Collections.TDictionary.AddOrSetValue)? – Andreas Rejbrand Dec 18 '20 at 12:57
  • no, when a value is duplicated, I need to rename it so that there are no identical values – Славентий Dec 18 '20 at 13:06
  • Sorry, that wasn't quite obvious to me (since the `e.g.` part didn't do or indicate any renaming). Well, then you need to use `ContainsKey` as David suggested. – Andreas Rejbrand Dec 18 '20 at 13:34
  • Personally I'd use the spring4d dictionary. It grinds my gears that you would do two hash lookups when one suffices, because of the limited design of the RTL class. – David Heffernan Dec 18 '20 at 13:45
  • @DavidHeffernan: That annoys me too. But personally I try to avoid third-party code if possible. The OP has to decide for themself. – Andreas Rejbrand Dec 18 '20 at 14:09
  • Thanks everyone! I did it through ContainsKey, I ruled out mistakes, and in the direction of the spring4d dictionary - you need to figure out how to use it and it might really be more rational. – Славентий Dec 18 '20 at 14:31
  • @Andreas You use the RTL and VCL all the time..... – David Heffernan Dec 18 '20 at 15:06

0 Answers0