How to insert as first element in dictionary?

前端 未结 5 1532
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 18:59

I have a dictionary structure, with multiple key value pairs inside.

myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
         


        
5条回答
  •  逝去的感伤
    2021-01-11 19:37

    Dictionary does not have an ordering. Any perceived order maintenance is by chance (and an artifact of a particular implementation including, but not limited to, bucket selection order and count).

    These are the approaches (just using the Base Class Libraries BCL) I know about:

    1. Lookup
      • .NET4, immutable, can map keys to multiple values (watch for duplicates during building)
    2. OrderedDictionary
      • Old, non-generic, expected Dictionary performance bounds (other two approaches are O(n) for "get(key)/set(key)")
    3. List>
      • .NET2/3 okay, mutable, more legwork, can map keys to multiple values (watch for duplicates in inserts)

    Happy coding.


    Creating a hash data-structure that maintains insertion order is actually only a slight modification of a standard hash implementation (Ruby hashes now maintain insertion order); however, this was not done in .NET nor, more importantly, is it part of the Dictionary/IDictionary contract.

提交回复
热议问题