Search code examples
delphigenericsdelphi-xe2deep-copytdictionary

Is there an easy way to copy the TDictionary content into another?


Is there a single method or easy way how to copy one TDictionary content into another ? Let's say I have the following declarations

type
  TItemKey = record
    ItemID: Integer;
    ItemType: Integer;
  end;
  TItemData = record
    Name: string;
    Surname: string;
  end;
  TItems = TDictionary<TItemKey, TItemData>;

var
  // the Source and Target have the same types
  Source, Target: TItems;
begin
  // I can't find the way how to copy source to target
end;

and I would like to copy 1:1 the Source to Target. Is there such method for this ?

Thanks!


Solution

  • TDictionary has a constructor that allows you to pass in another collection object, which will create the new one by copying the contents of the original. Is that what you are looking for?

    constructor Create(Collection: TEnumerable<TPair<TKey,TValue>>); overload;
    

    So you would use

    Target := TItems.Create(Source);
    

    And Target would be created as a copy of Source (or at least contain all the items in Source).