0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • If the items are to be identified by sequential integer values then surely a dictionary is the wrong collection. Don't you want to hold them in a list or array? – David Heffernan Sep 28 '19 at 07:15

1 Answers1

0

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.

Stefan Glienke
  • 20,860
  • 2
  • 48
  • 102