开发者

How can I change the Key value in a Delphi TDictionary or TObjectDictionary?

开发者 https://www.devze.com 2023-02-22 20:24 出处:网络
Can I change the key in a TDictionary, without changing the value? To explain, I am using a TObjectDictionary, which is derived from the TDictionary in the Delphi XEGenerics.Collections unit. This is

Can I change the key in a TDictionary, without changing the value?

To explain, I am using a TObjectDictionary, which is derived from the TDictionary in the Delphi XE Generics.Collections unit. This is all fine, except that I also need to be able to change the key value for the object stored.

My first attempt is as follows:

MyObject := MyDictionary.Items[OldKeyValue];
MyDictionary.Remove(OldKeyValue);
MyDictionary.Add(NewKeyValue, MyObject);

The problem with this is that the Remove() causes the object to be Free'd. I tried doing a AddOrSetValue to change the value to nil first, but that too Free's the object. Since I've 开发者_JAVA技巧told the dictionary it owns them, this is fair enough. There is though no additional function in TObjectDictonary to remove without Free, so I therefore move to trying to change the Key in the dictionary without altering the value. However I am unable to see anything that looks like it will do this in the Delphi XE help. Is this possible at all? If not, I'll go back to using a Dictionary and free it all myself.


Call TDictionary<TKey,TValue>.ExtractPair(const Key: TKey) and you will get hold of the key and the value, but the value will not have been freed. You can then add it back in with a different key.

The ExtractPair() method returns a TPair<TKey,TValue> which is simply a record containing a key and its associated value.

The code might look something like this:

type
  TMyKey = string;
  TMyValue = TMyObject;

procedure ChangeKey(dict: TDictionary<TMyKey,TMyValue>; OldKey, NewKey: TMyKey);
var
  Pair: TPair<TMyKey,TMyValue>;
begin
  Pair := dict.ExtractPair(OldKey);
  dict.Add(NewKey, Pair.Value);
end;
0

精彩评论

暂无评论...
验证码 换一张
取 消