小编典典

字典中元素的顺序

c#

我的问题是关于枚举Dictionary元素

// 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));
}

元素将以什么顺序列出?我可以强制顺序为字母顺序吗?


阅读 936

收藏
2020-05-19

共1个答案

小编典典

字典中元素的顺序是不确定的。根本没有为哈希表定义顺序的概念。因此,不要依赖于将元素添加到字典的顺序来枚举。不能保证。

从文档引用:

出于枚举的目的,字典中的每个项目都被视为KeyValuePair<TKey, TValue>代表值及其键的结构。返回项目的顺序是不确定的。

2020-05-19