Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 422
mj2008 Avatar asked Apr 08 '11 13:04

mj2008


1 Answers

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;
like image 124
David Heffernan Avatar answered Oct 12 '22 14:10

David Heffernan