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

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

问题描述

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

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 结构,表示一个值及其键.项目返回的顺序未定义.

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天全站免登陆