Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 812
Martin Reiner Avatar asked Mar 20 '12 13:03

Martin Reiner


People also ask

How do I copy a dictionary from one dictionary to another?

The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

What are the ways to copy a dictionary d2 to d1?

Copy a dictionary with a for loop To copy a dictionary it is also possible to use a for loop: >>> d1 = {'a':1,'b':2} >>> d2 = {} >>> for key in d1: ... d2[key] = d1[key] ...

How do you shallow copy a dictionary in Python?

The simplest way to create a copy of a Python dictionary is to use the . copy() method. This method returns a shallow copy of the dictionary.


1 Answers

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).

like image 120
Jerry Gagnon Avatar answered Nov 07 '22 20:11

Jerry Gagnon