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 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With