Ordered Dictionary?

I don’t really understand why the order of items needs to be preserved, so my answer may be a little off. But can’t you just create a subclass of Dictionary and override methods as needed?

Class OrderedDictionary
Inherits Dictionary

  Sub Clear
    redim self.mPreservedKeyOrder(-1)
    super.Clear
  End Sub

  Sub Constructor(ParamArray entries as Pair)
    super.Constructor
    for each p as Pair in entries
      self.Value(p.Left) = p.Right
    next p
  End Sub

  Function PreservedKeyOrder() as Variant()
    return self.mPreservedKeyOrder
  End Function

  Sub Remove(key as Variant)
    dim index as Integer = self.mPreservedKeyOrder.IndexOf(key)
    self.mPreservedKeyOrder.Remove(index)
    super.Remove(key)
  End Sub

  Sub Value(key as Variant, Assigns data as Variant)
    // do not replace existing values, as @npalardy mentioned...
    if not self.HasKey(key) then
      self.mPreservedKeyOrder.Append(key)
      super.Value(key) = data
    end if
  End Sub

  Private Property mPreservedKeyOrder() as Variant

End Class

You could then loop through the list of keys returned by PreservedKeyList to retrieve the items in the order they were added.

This code is completely untested, but should get you on the right track (if I understood things right).

1 Like