2012-03-20 12 views
12

1つのTDictionaryコンテンツを別の方法でコピーする方法は1つだけですか?ターゲットに1出典: のは、私は次の宣言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をコピーしたいとしましょう。このための方法はありますか?

ありがとうございます!

答えて

21

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

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

だから、

Target := TItems.Create(Source); 

を使用すると、ソースのコピーが(あるいは、少なくともソースのすべての項目が含まれている)として、ターゲットが作成されます。

+3

+1私はGeneric TDictionaryをかなり使っていますが、これは分かりません。ありがとう。 – Justmade

+2

+1私からも、このオーバーロードについて知りませんでした、私は今、とても怒っています! -.- – ComputerSaysNo

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; 
+0

あなたがLNewKeyを割り当てる理由を説明することができます:= LKey;式LTarget.Add(LKey、LSource.Items [LKey])でLkeyを2回だけ使用するのではなく、 – RobertFrank

+0

@Robert、はい、それはテストから残っています、ありがとう、私はそれを削除します... – ComputerSaysNo

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; 

使い方キーのあなたの定義値に従って:

TDictionaryHelpers<TItemKey, TItemData>.CopyDictionary(LSource, LTarget); 
関連する問題