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

2 .net linq

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

我正在使用一个Dictionary<int, classname>和我一起寻找.Find或IndexOf与Linq无济于事.

Mic*_*tum 6

字典没有排序,因此Key确实没有任何索引.请在此处查看我的问题:通过数字索引访问Dictionary.Keys Key

使用OrderedDictionary,它有一个带Int索引器.

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

foreach(KeyValuePair kvp in yourDict)
Run Code Online (Sandbox Code Playgroud)

如果键是Int而你想要下一个,请使用

var newkey = oldkey+1;
if(yourdict.ContainsKey(newkey)){
    var newvalue = yourdict[newkey];
}
Run Code Online (Sandbox Code Playgroud)

如果int不是顺序的,你可以使用

var upperBound = d.Max(kvp => kvp.Key)+1; // to prevent infinite loops
while(!yourdict.ContainsKey(newkey) && newkey < upperBound) {
    newkey++;
}
Run Code Online (Sandbox Code Playgroud)

或者,或者:

var keys = (from key in yourdict.Keys orderby key select key).ToList();
// keys is now a list of all keys in ascending order
Run Code Online (Sandbox Code Playgroud)

  • 或OrderedDictionary:http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary_members.aspx (2认同)