2010-11-02 67 views

回答

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版本中,此行为可能会发生变化。

+0

这太好了。 Hashtable和Dictionary的替代方法很简单。此外,关于Dictionary默认排序顺序的注释非常有用。 – 2010-11-02 19:06:15

+0

请记住添加: using System.Collections.Specialized; – 2012-08-27 00:11:20

5

如果这是你需要有效跟踪的东西,那么你正在使用错误的数据结构。相反,您应该使用SortedDictionary,其中密钥标有添加时间的索引(或时间戳)以及基于索引(或时间戳)比较两个密钥的自定义IComparer

3

.NET中是否有任何散列表或字典允许您按照添加到集合的顺序访问它的.Index属性?

号可以enumarate了在Hastable或字典中的所有项目,但这些都不是gaurenteed是在任何种类的顺序(最有可能他们不是)

你必须要么使用一个不同的数据结构(如SortedDictionary或SortedList)或使用单独的列表来存储它们添加的顺序。你会想要将有序列表和你的字典/散列表包装在另一个类中来保持它们的同步。

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... 
} 
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

2

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