查找密钥的索引?字典.NET

时间:2010-07-23 01:55:56

标签: .net linq

我需要做currentKey + 1。所以我想找到键值的索引并获取下一个键(或者如果在结束时首先)。如何找到密钥的当前索引?

我正在使用Dictionary<int, classname>,我在Linq中寻找.Find或IndexOf无济于事。

3 个答案:

答案 0 :(得分:6)

字典没有排序,因此Key实际上没有任何索引。请在此处查看我的问题:Accessing a Dictionary.Keys Key through a numeric index

使用OrderedDictionaryindexer that takes an Int

编辑:'我不确定我明白你想要什么。如果要迭代字典,只需使用

foreach(KeyValuePair kvp in yourDict)

如果密钥是Int并且您想要下一个,请使用

var newkey = oldkey+1;
if(yourdict.ContainsKey(newkey)){
    var newvalue = yourdict[newkey];
}

如果整数不是连续的,您可以使用

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

答案 1 :(得分:2)

正如迈克尔·斯图姆所指出的,Dictionary<TKey, TValue>没有排序(它是一个哈希表),所以没有键的“索引”。相反,您可以使用 (顾名思义)排序的SortedList并提供IndexOfKey方法。

请注意,Dictionary<TKey, TValue>的效果特征与SortedList<TKey, TValue>不同。虽然Dictionary对于插入和删除是O(1),但SortedList是O(logn)。

答案 2 :(得分:2)

不使用不同的集合,就可以这样做。虽然我不确定这是多么有效。

classIndex = classes.ToList().IndexOf(new KeyValuePair<int, classname>(newKey, classes[newKey]));