在字典中元素的顺序字典、顺序、元素

2023-09-02 10:19:38 作者:黄昏中等待夜幕的降临

我的问题是关于枚举字典元素

My question is about enumerating Dictionary elements

// Dictionary definition
private Dictionary<string, string> _Dictionary = new Dictionary<string, string>();

// add values using add

_Dictionary.Add("orange", "1");
_Dictionary.Add("apple", "4");
_Dictionary.Add("cucumber", "6");

// add values using []

_Dictionary["banana"] = 7;
_Dictionary["pineapple"] = 7;

// Now lets see how elements are returned by IEnumerator
foreach (KeyValuePair<string, string> kvp in _Dictionary)
{
  Trace.Write(String.Format("{0}={1}", kvp.Key, kvp.Value));
}

在什么样的顺序将是要素枚举?我可以强制为了按字母顺序排列?

In what order will be the elements enumerated? Can I force the order to be alphabetical?

推荐答案

在字典中元素的顺序是不确定性。秩序的概念根本没有定义哈希表。所以不要依赖于枚举的元素被添加到字典中的顺序相同。这不能保证。

The order of elements in a dictionary is non-deterministic. The notion of order simply is not defined for hashtables. So don't rely on enumerating in the same order as elements were added to the dictionary. That's not guaranteed.

报价从DOC :

为了枚举,在字典中的每个项目被视为 KeyValuePair&LT; TKEY的,TValue&GT; 结构重新presenting价值和它的关键。在其中的物品的返回顺序是不确定的。

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.