按顺序对Hashtable进行排序

时间:2010-11-02 18:02:22

标签: c# .net vb.net collections hashtable

这与How to keep the order of elements in hashtable类似,但.NET除外。

.NET中是否有HashtableDictionary允许您按照添加到集合中的顺序访问其.Index属性?

6 个答案:

答案 0 :(得分:5)

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的未来版本中,此行为可能会更改。

答案 1 :(得分:4)

如果这是您需要有效跟踪的内容,那么您使用的是错误的数据结构。相反,您应该使用SortedDictionary,其中键被标记为添加时间的索引(或时间戳)和自定义IComparer,根据索引(或时间戳)比较两个键

答案 2 :(得分:3)

  

.NET中是否有任何Hashtable或Dictionary允许您按照添加到集合中的顺序访问该条目的.Index属性?

没有。你可以对Hastable或Dictionary中的所有项目进行创建,但这些项目并不是以任何形式排列的(很可能不是这样)

您必须完全使用不同的数据结构(例如SortedDictionary或SortedList)或使用单独的列表来存储它们的添加顺序。您可能希望将有序列表和字典/哈希表包装在另一个类中以使它们保持同步。

答案 3 :(得分:3)

您可以使用单独的列表按添加顺序存储元素。以下示例中的内容:

public class ListedDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    List<TValue> _list = new List<TValue>();
    Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey,TValue>();

    public IEnumerable<TValue> ListedValues
    {
        get { return _list; }
    }

    public void Add(TKey key, TValue value)
    {
        _dictionary.Add(key, value);
        _list.Add(value);
    }

    public bool ContainsKey(TKey key)
    {
        return _dictionary.ContainsKey(key);
    }

    public ICollection<TKey> Keys { get { return _dictionary.Keys; } }

    public bool Remove(TKey key)
    {
        _list.Remove(_dictionary[key]);
        return _dictionary.Remove(key);
    }

    // further interface methods...
}

答案 4 :(得分:2)

看一下OrderedDictionary类。您不仅可以通过键访问它,还可以通过索引(位置)访问它。

答案 5 :(得分:1)

另一种方法是创建一个结构数组,而不是使用

dictionary.Add{"key1","value1"}

使用键/值创建结构,如:

public struct  myStruct{
    private string _sKey;
    public string sKey{
        get { return _sKey; }
        set { _sKey = value; }
    }
    private string _sValue;
    public string sValue {
        get { return _sValue; }
        set { _sValue = value; }
    }
}

// create list here
List<myStruct> myList = new List<myStruct>();

// create an instance of the structure to add to the list
myStruct item = new myStruct();
item.sKey = "key1";
item.sValue = "value1";

// then add the structure to the list
myList.Add(item);

使用此方法,您可以毫不费力地在列表中添加额外的维度,只需在结构中添加新成员。

注意,如果在添加项目后需要修改列表中的项目,则必须将结构更改为类。有关此问题的详情,请参阅此页面:error changing value of structure in a list