.net - 查找键的索引?词典.NET

标签 .net linq

我需要做 currentKey+1。所以我想找到键值的索引并获取下一个键(如果在末尾则为第一个)。我如何找到 key 的当前索引?

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

最佳答案

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

使用 OrderedDictionary它有一个 indexer 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

关于.net - 查找键的索引?词典.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35317465/

相关文章:

c# - Linq 选择列表中存在的对象(A,B,C)

.net - 如何设置 .Net 应用程序以使用 firebird Entity Framework 提供程序(对于嵌入式数据库)

c# - 我如何依赖注入(inject) SignInManager?

c# - 在 Bamboo 中运行时不同的 .NET 构建结果

c# - 删除 LINQ to EF 中的关联数据

c# - Entity Framework 错误,一张表总是超时

c# - .Net 的 Java AST 解析器

c# - String.Split 能否区分 char 的单个实例和多个实例?

arrays - Guid 数组到字符串和返回的最快转换?

C# LINQ 按小时从数据表中获取记录