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

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

元素的列举顺序是什么?我可以强制按字母顺序排列吗?

推荐答案

字典中元素的顺序是不确定的.没有为哈希表定义顺序的概念.因此,不要依赖于在字典中添加元素时按相同的顺序枚举.这还不能保证.

报价from the doc:

出于枚举的目的,字典中的每一项都被视为表示一个值及其键的KeyValuePair<TKey, TValue> struct .返回项目的顺序未定义.

.net相关问答推荐

在数据网格中:如何在更改单元格 A 中的值后显示单元格 B 中的更改

无法使用 int.Parse 从字符串转换值

Dictionary.FirstOrDefault() 如何判断是否找到了结果

xunit Assert.ThrowsAsync() 不能正常工作?

RNGCryptoServiceProvider 的优缺点

如何在 WPF 应用程序中使用 App.config 文件?

使用只读属性或方法?

支持 HTTPS 的 Httplistener

隐式与显式接口实现

日期时间是什么意思?在 C# 中是什么意思?

如何更改 double.ToString() 中小数点的符号?

所有数组在 C# 中都实现了哪些接口?

ILookup 接口与 IDictionary

如何从 XDocument 获取 Xml 作为字符串?

哪个密码字符在 winforms 文本框中显示黑点 (•)?

何时何地使用 GetType() 或 typeof()?

如何知道 DateTime 是否在 C# 中的 DateRange 之间

当它被抛出和捕获时,不要在那个异常处停止调试器

检测到包降级警告(dotnet core,vs 2017)

嵌套捕获组如何在正则表达式中编号?