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

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

问题描述

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

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.

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

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