14

ある TDictionary コンテンツを別のコンテンツにコピーする単一の方法または簡単な方法はありますか? 次の宣言があるとしましょう

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;

ソースをターゲットに 1:1 でコピーしたいと思います。これにはそのような方法はありますか?

ありがとう!

4

4 に答える 4

27

TDictionaryには、別のコレクションオブジェクトを渡すことができるコンストラクターがあります。このコンストラクターは、元のオブジェクトの内容をコピーして新しいオブジェクトを作成します。それはあなたが探しているものですか?

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

だからあなたは使うでしょう

Target := TItems.Create(Source);

また、ターゲットはソースのコピーとして作成されます(または少なくともソース内のすべてのアイテムが含まれます)。

于 2012-03-20T13:24:19.877 に答える
1

さらに先に進みたい場合は、別のアプローチを次に示します。

type
  TDictionaryHelpers<TKey, TValue> = class
  public
    class procedure CopyDictionary(ASource, ATarget: TDictionary<TKey,TValue>);
  end;

...implementation...

{ TDictionaryHelpers<TKey, TValue> }

class procedure TDictionaryHelpers<TKey, TValue>.CopyDictionary(ASource,
  ATarget: TDictionary<TKey, TValue>);
var
  LKey: TKey;
begin
  for LKey in ASource.Keys do
    ATarget.Add(LKey, ASource.Items[ LKey ] );
end;

KeyValueの定義に応じた使用法:

TDictionaryHelpers<TItemKey, TItemData>.CopyDictionary(LSource, LTarget);
于 2012-03-20T13:29:56.687 に答える
0

これでうまくいくはずだと思います:

var
  LSource, LTarget: TItems;
  LKey: TItemKey;
begin
  LSource := TItems.Create;
  LTarget := TItems.Create;
  try
    for LKey in LSource.Keys do 
      LTarget.Add(LKey, LSource.Items[ LKey ]);
  finally
    LSource.Free;
    LTarget.Free;
  end; // tryf
end;
于 2012-03-20T13:19:02.587 に答える