Iterating over Dictionary with foreach, in what order is this done?

回眸只為那壹抹淺笑 提交于 2019-12-23 07:02:32

问题


Say I have a Dictionary, and I add each key and value entry in a specific order.
Now, if I want later to be able to iterate this Dictionary in the same order entries were added, is it the order I get with simple foreach loop on this dictionary?

If not, I will be glad to hear how can I do that, I know this can be done easily with List instead of Dictionary but I don't want to.

Thanks


回答1:


Normal Dictionary does not guarantee order of items.

You need OrderedDictionary if you want to maintain order items where added to it. Note that there is no generic version of this class in .Net framework, so either have to give up some type-safety or find other implementation (i.e. https://www.codeproject.com/Articles/18615/OrderedDictionary-T-A-generic-implementation-of-IO as suggested by Tim S).

Alternatively if O(log n) lookup is fine and keys should be sorted - SortedDictionary.




回答2:


Sounds like what you want is a Queue<T>: http://msdn.microsoft.com/en-us/library/7977ey2c.aspx

Add your KeyValuePair<T, U> items to it in the order you want and then foreaching over it will be in first-in/first-out order.




回答3:


Dictionarys are hash tables, which means that you can't guarantee that iterating the pairs will return them in the same order you added them.

Each pair is a KeyValuePair<T_K, T_V>, so you could have a List<KeyValuePair<string, string>> that would let you iterate in the order you add them if that's what you need.




回答4:


The internal sort of the dictionary will depend on the hash function used. However if you need a sorted view of the data, you can use Enumerable.OrderBy.



来源:https://stackoverflow.com/questions/13998185/iterating-over-dictionary-with-foreach-in-what-order-is-this-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!