I need a delphi key/value collection that will allow me to iterate over the collection in the same order the key/value pairs were inserted/added.
TList<T>
guarantees order but TDictionary<T1, T2>
does not.
I guess I could always define a TList<TPair<Key, Value>>
but it would be more cumbersome to work with.
Is there a built-in collection type that would meet my requirements or would wrapping TList<TPair<Key, Value>>
be my best option? Or perhaps it would be better to have a TList<Key>
and a TDictionary<Key, Value>
and iterate through the list.
ArrayDeque a deque can used for simple que and stack so you want to have ''first in first out'' or ''first in last out'' behaviour, both require that the ArrayDeque maintains insertion order. In this case the insertion order is maintained as a central part of the classes contract.
A key-value database stores data as a collection of key-value pairs in which a key serves as a unique identifier. Both keys and values can be anything, ranging from simple objects to complex compound objects.
Every dictionary is an unordered collection of key-value pairs. You can iterate over a dictionary using a for - in loop, decomposing each key-value pair into the elements of a tuple.
It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted.
If your key type is string
and your value type is some descendant of TObject
, use a TStringList
. Store your values in the Objects
array property.
SL.AddObject('foo', obj1);
SL.Add('bar');
i := SL.IndexOf('bar');
SL.Objects[i] := obj2;
Set the OwnsObjects
property if you need to.
the DeHL collections library contains a lot of "Ordered Dictionary"-like classes. The ordered ones use trees (which have order) instead of hash maps which are unordered.
I believe the TSortedDistinctMultiMap
might be what you need, if you want to enforce uniqueness, and if you don't want to enforce Key
value uniqueness, then there are other choices (without Distinct
in the class name) that will be close to what you need.
Update 2017: The DeHL library is no longer maintained.
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