按顺序排序哈希表在创建它 [英] Sorting Hashtable by Order in Which It Was Created

查看:160
本文介绍了按顺序排序哈希表在创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是类似于如何保持元素的顺序在哈希表,除了.NET。

This is similar to How to keep the order of elements in hashtable, except for .NET.

有没有的Hashtable 词典在.net中,使您可以访问它的 .Index 属性在它被添加到集合中的顺序录入?

Is there any Hashtable or Dictionary in .NET that allows you to access it's .Index property for the entry in the order in which it was added to the collection?

推荐答案

A 的NameValueCollection 可以检索通过索引元素(但你不能要求一个特定密钥索引或元件)。因此,

A NameValueCollection can retrieve elements by index (but you cannot ask for the index of a specific key or element). So,

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),当您添加一个键多次:

However, it behaves oddly (compared to an IDictionary) when you add a key multiple times:

var coll = new NameValueCollection();
coll.Add("Z", "1");
coll.Add("A", "2");
coll.Add("Z", "3");
Console.WriteLine(coll[0]); // prints "1,3"

该行为是有据可查的,但是。

The behaviour is well documented, however.

注意:的NameValueCollection 做的不可以实施的IDictionary

顺便说一句:词典< K,V> 没有任何指标可以使用,但只要你只添加元素,永远不会删除任何的顺序的元素是插入顺序。请注意,这是微软目前实施的细节:文件明确规定的顺序是随机的,所以这种行为可以在.NET Framework或单声道的未来版本更改

As an aside: Dictionary<K,V> does not have any index you can use, but as long as you only add elements, and never remove any, the order of the elements is the insertion order. Note that this is a detail of Microsoft's current implementation: the documentation explicitly states that the order is random, so this behavior can change in future versions of the .NET Framework or Mono.

这篇关于按顺序排序哈希表在创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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