这类似于 How to keep the order of elements in hashtable ,.NET 除外。
.NET 中是否有任何 Hashtable
或 Dictionary
允许您访问它的 .Index
属性以获取条目的顺序它被添加到收藏中了吗?
最佳答案
A NameValueCollection
可以通过索引检索元素(但您不能要求特定键或元素的索引)。所以,
var coll = new NameValueCollection();
coll.Add("Z", "1");
coll.Add("A", "2");
Console.WriteLine("{0} = {1}", coll.GetKey(0), coll[0]); // prints "Z = 1"
但是,当您多次添加一个键时,它的行为很奇怪(与 IDictionary 相比):
var coll = new NameValueCollection();
coll.Add("Z", "1");
coll.Add("A", "2");
coll.Add("Z", "3");
Console.WriteLine(coll[0]); // prints "1,3"
但是,该行为已被详细记录。
注意:NameValueCollection
不实现IDictionary
.
顺便说一句:Dictionary<K,V>
没有任何可以使用的索引,但是只要您只添加元素而不删除任何元素,元素的顺序就是插入顺序。请注意,这是 Microsoft 当前实现的一个细节:文档明确指出顺序是随机的,因此此行为可能会在 .NET Framework 或 Mono 的 future 版本中发生变化。
关于c# - 按创建顺序对哈希表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4080667/