How to insert element in first index in dictionary?

前端 未结 9 1053
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 10:09

Is there a method or technique that allows you to insert an element into a Dictionary guaranteeing that the item is in the first index of t

9条回答
  •  被撕碎了的回忆
    2020-12-17 10:42

    By not using a dictionary.

    Dictionary is implemented as a hash-table. The position of keys internal to the dictionary depends upon the hash-code, the means by which that hash-code was reduced further to provide an index into its internal structure, and the order of insertion in an entirely implementation-dependant way.

    This isn't the only way to implement a dictionary. SortedDictionary uses a tree structure internally and so always keeps keys in an order. In this case we still can't insert something in the beginning, rather we insert something and it gets put in the appropriate place.

    If ordering is what you care about most, then you don't want a puredictionary at all. Rather you want either a List> or you want a structure that offers both the functionality of a list and of a dictionary, which is provided by OrderedDictionary. This isn't generic, but you can easily create a generic wrapper around it (doesn't give the performance benefits of internally using generics, but does give type-safety in use).

提交回复
热议问题