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;

我想将 Source 1:1 复制到 Target。有这样的方法吗?

谢谢!

4

4 回答 4

27

TDictionary 有一个构造函数,允许您传入另一个集合对象,该对象将通过复制原始集合的内容来创建新的集合对象。那是你要找的吗?

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

所以你会使用

Target := TItems.Create(Source);

Target 将被创建为 Source 的副本(或至少包含 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 回答
0

在打算分配时构造一个新实例可能会产生副作用,例如在别处使对象引用失效。通用方法可能不会深度复制引用的类型。

我会采用更简单的方法:

unit uExample;

interface

uses
  System.Generics.Collections;

type 
  TStringStringDictionary = class(TDictionary<string,string>)
  public
    procedure Assign(const aSSD: TStringStringDictionary);
  end;

implementation

procedure TStringStringDictionary.Assign(const aSSD: TStringStringDictionary );
var
  lKey: string;
begin
  Clear;
  for lKey in aSSD.Keys do
    Add(lKey, aSSD.Items[lKey]); // Or use copy constructors for objects to be duplicated
end;

end.
于 2021-02-20T22:38:37.763 回答