当我通过词典(.NET通用数据结构)迭代它会以相同的顺序,我加入他们吗?当我、数据结构、会以、词典

2023-09-04 23:47:22 作者:空心計

我有,我通常用钥匙进入一本字典,所以我需要快速随机访问读取。然而,对于一个功能我需要处理每一个项目在字典中,其中的顺序是非常重要的。这似乎在测试中是工作确定。是否确定取决于项目在字典中的顺序?

I have a dictionary that I normally access with a key, so I need fast random access reads. However for one function I need to process every item in the dictionary where the order is important. It seems to be working OK in tests. Is it OK to depend on the order of items in a dictionary?

推荐答案

没有。如果你需要保持一个订单,你应该有一个项目名单。你可以封装了所有你需要在你自己的集合类的操作,这将同时更新字典和列表在同一时间。

No. If you need to keep an order, you should have a list of items as well. You could encapsulate all the operations you need in your own collection class, which would update both the dictionary and the list at the same time.

这是不幸的.NET没有一本字典,支持这个本身 - 这是一个相当普遍的要求 - Java那样,为的 LinkedHashMap的。

It's unfortunate that .NET doesn't have a dictionary which supports this itself - it's a reasonably common request - Java does, as LinkedHashMap.