如何获得Dictionary元素的相对位置? [英] How to get the relative position of a Dictionary element?
问题描述
我有下一个C#代码:
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("a", 3);
d.Add("b", 1);
d.Add("c", 0);
d.Add("d", -1);
d.Add("e", -9);
在搜索键 c时,我想获取该键的位置,即2。我寻找键 e,我想得到4。如果找不到该元素,则相对位置可能是-1。
When searching the key "c" I want to get the position of this key, i.e. 2. If I look for the key "e", I want to get 4. If the element is not found the relative position could be -1.
已添加:
除非您有更好的主意,否则我想在行号中填充某些值的矩阵,该值由找到的字典元素的相对位置指示。该列也适用,但使用不同的字典。例如:
Added: Unless you have a better idea, I want to populate a matrix with certain values in a row number indicated by the relative position of a dictionary element found. The same applies for the column but using a different dictionary. An example:
n4 n2 n1 n3 n9 . . .
a 4/4
b 2 8
c
d 8/2
e 4/3
.
.
.
其中a,b,c,d,e,...是 d的键和n4,n2,n3,n9是第二本字典的键。
Where a,b,c,d,e,... are the keys of dictionay "d" and n4,n2,n3,n9 are the keys of a second dictionary.
我怎么能得到这个?
推荐答案
在 Dictionary<,>
中没有位置之类的东西-这是一个无序的集合。
There's no such thing as a "position" within a Dictionary<,>
- it's an unordered collection.
也有类似的按键排序的集合- SortedList<,>
和 SortedDictionary<,>
。请注意,这些是按键而不是插入时间排序的。不清楚您想要哪个。
There are similar collections sorted by key - SortedList<,>
and SortedDictionary<,>
. Note that those are ordered by key rather than insertion time though. It's not clear which you want.
这篇关于如何获得Dictionary元素的相对位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!