What's the best way to re-index a TDictionary?

182 Views Asked by At

I have a TObjectDictionary<Integer, TMyObject>, and TMyObject has an ID field that's the key. The dictionary owns the values. The keys originally come from a sequence generator, so as deletes and inserts occur, the key values become non-sequential in the dictionary, and I need them to be sequential. I could pull all the objects into a separate TList, renumber their IDs, clear the dictionary and re-add the objects with their now-sequential keys, but that seems awfully inelegant. Is there a better way to do this?

Also, how do I tell a TObjectDictionary that it no longer owns its values?

1

There are 1 best solutions below

0
Stefan Glienke On

If the key is retrievable from the value then it is probably not the best idea to store that inside a TDictionary as then you can't easily rehash all items when their key property changed. That combined with the fact that you can only use ExtractPair to keep objects owned by the dictionary alive which is terribly ineffective or hack your way to the private FOwnerships field.

As the key/id comes from a sequence generator the insertion order probably happens to be in increasing order which might be the indicator to put the items into a list and keep them ordered by ID. Lookup can then be done with a binary search.

Unless you are fancy and implement your own search tree to satisfy whatever requirements you have.