查找密钥索引?字典.NET [英] Find index of a key? Dictionary .NET
问题描述
我需要做currentKey + 1.因此,我想找到键值的索引并获取下一个键(如果最后是第一个键).如何找到密钥的当前索引?
I need to do currentKey+1. So i would like to find the index of the key value and get the next key (or first if at end). How do i find the current index of the key?
我正在使用Dictionary<int, classname>
,并且我使用Linq寻找.Find或IndexOf无济于事.
I am using a Dictionary<int, classname>
and i looked for .Find or IndexOf with Linq to no avail.
推荐答案
字典未排序,因此Key确实没有任何索引.在这里看到我的问题:访问字典.键通过数字索引键
Dictionaries are not sorted, so the Key doesn't have any index really. See my question here: Accessing a Dictionary.Keys Key through a numeric index
使用 OrderedDictionary 带有Int的索引器.
'我不确定我了解您想要什么.如果您想遍历字典,只需使用
'm not really sure I understand what you want. If you want to iterate through a Dictionary, just use
foreach(KeyValuePair kvp in yourDict)
如果键是一个Int,而您想要下一个,请使用
If the key is an Int and you want the next, use
var newkey = oldkey+1;
if(yourdict.ContainsKey(newkey)){
var newvalue = yourdict[newkey];
}
如果整数不是连续的,则可以使用
If the ints are not sequential, you can use
var upperBound = d.Max(kvp => kvp.Key)+1; // to prevent infinite loops
while(!yourdict.ContainsKey(newkey) && newkey < upperBound) {
newkey++;
}
或者,或者:
var keys = (from key in yourdict.Keys orderby key select key).ToList();
// keys is now a list of all keys in ascending order
这篇关于查找密钥索引?字典.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!