我有一本字典的结构,里面多个键值对。
I have a dictionary structure, with multiple key value pairs inside.
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
我的字典被用作数据源的一些控制。在控制的下拉我看的项目都是这样的:
My dictionary is used as a data source for some control. In the control's dropdown I see the items are like this:
key1
key2
key3
的顺序看起来与我的字典。 我知道字典是不是像ArrayList的 - 你可以得到索引左右。 我不能使用sortedDictionary。 现在我需要多一个键值对添加到这个字典在某些时候我的计划,我希望它具有相同的效果,因为我做到这一点:
The order looks identical to my dictionary. I know Dictionary is not like arrayList - you can get the index or so. I cannot use sortedDictionary. Now I need to add one more key value pair to this dictionary at some point of my program and I hope it has the same effect as I do this:
myDict.Add(newKey, newValue);
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
如果我这样做,我知道则newkey将在我的控制作为第一个元素显示。
If I do this, I know newKey will display in my control as first element.
我有一个想法创造一个tempDict,把每对myDict到tempDict,然后清除myDict,再加入双回是这样的:
I have an idea to create a tempDict, put each pair in myDict to tempDict, then clear myDict, then add pairs back like this:
myDict.Add(newKey, newValue);
myDict.Add(key1, value1);
myDict.Add(key2, value2);
myDict.Add(key3, value3);
有没有更好的办法比这?
Is there better way than this?
谢谢!
字典< K,V>
没有的没有的有一个排序。任何知觉秩序的维护是一个偶然的机会(和特定的实现产物,包括但不限于,水桶选择顺序和次数)。
Dictionary<K,V>
does not have an ordering. Any perceived order maintenance is by chance (and an artifact of a particular implementation including, but not limited to, bucket selection order and count).
这些都是方法(只使用基类库BCL )我知道的:
These are the approaches (just using the Base Class Libraries BCL) I know about:
查找&LT; K,V&GT;
.NET4,一成不变的,可以(建设过程中注意重复)键映射为多个值
Lookup<K,V>
.NET4, immutable, can map keys to multiple values (watch for duplicates during building)
旧,非通用,预计字典的性能界限(其他两种方法 O(N)
为获得(键)/套(键))
Old, non-generic, expected Dictionary performance bounds (other two approaches are O(n)
for "get(key)/set(key)")
.NET2 / 3还行,可变的,多跑腿,可以映射键多个值(看在插入重复)
快乐编码。
创建散列数据结构,用于维护插入顺序实际上是一个标准的哈希实施只有轻微的修改(Ruby的哈希值现在保持插入顺序);然而,这并没有在.NET做也不行,更重要的是它的字典/ IDictionary的合同的一部分。
Creating a hash data-structure that maintains insertion order is actually only a slight modification of a standard hash implementation (Ruby hashes now maintain insertion order); however, this was not done in .NET nor, more importantly, is it part of the Dictionary/IDictionary contract.