词典中元素的顺序 [英] The order of elements in Dictionary

查看:134
本文介绍了词典中元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

引用从文档


为枚举目的,字典中的每个项目都被视为 KeyValuePair< TKey,TValue> 表示值及其键的结构。未定义项目的顺序。

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.

这篇关于词典中元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆