资讯动态

Dictionary已知内层Key查找Value

发布时间:2026/9/1 7:31:34 来源:尧图企业网站定制
场景说明结构Dictionarystring, Dictionarystring, string AppAttributes已知内层Key要查找对应Value存在两种需求只找第一个匹配就返回找到所有外层Key 对应Value可能多个外层字典包含同一个内层Key方式1找到第一条匹配找到即退出性能更好string targetInnerKey 你已知的内层Key; string result null; string findOuterKey null; if (AppAttributes ! null) { foreach (var outerKvp in AppAttributes) { var innerDict outerKvp.Value; if (innerDict null) continue; if (innerDict.TryGetValue(targetInnerKey, out string val)) { result val; findOuterKey outerKvp.Key; break; // 找到第一个直接跳出循环 } } } if (result ! null) { Console.WriteLine($外层Key:{findOuterKey} 值:{result}); }方式2查找全部匹配存在多个外层拥有相同内层key时使用string targetInnerKey 你已知的内层Key; // 存储外层Key - 对应值 Dictionarystring, string matchResult new Dictionarystring, string(); if (AppAttributes ! null) { foreach (var outerKvp in AppAttributes) { var innerDict outerKvp.Value; if (innerDict null) continue; if (innerDict.TryGetValue(targetInnerKey, out string val)) { matchResult.Add(outerKvp.Key, val); } } }方式3LINQ 简写版本string targetInnerKey 你已知的内层Key; // 获取第一条 var firstMatch AppAttributes? .SelectMany(o o.Value .Where(i i.Key targetInnerKey) .Select(i new { OuterKey o.Key, Value i.Value })) .FirstOrDefault(); if (firstMatch ! null) { string value firstMatch.Value; string outerKey firstMatch.OuterKey; } // 获取所有匹配 var allMatchList AppAttributes? .SelectMany(o o.Value .Where(i i.Key targetInnerKey) .Select(i new { OuterKey o.Key, Value i.Value })) .ToList();⚠️重要提醒这种结构无法直接通过内层Key快速索引必须遍历所有外层字典。如果查询频繁建议额外建立反向索引Dictionarystring, List(string OuterKey, string Value)补充封装成方法直接复制使用/// summary /// 根据内层Key查找第一个对应的值 /// /summary public bool TryGetByInnerKey(string innerKey, out string value, out string outerKey) { value null; outerKey null; if (AppAttributes null) return false; foreach (var outer in AppAttributes) { if (outer.Value null) continue; if (outer.Value.TryGetValue(innerKey, out value)) { outerKey outer.Key; return true; } } return false; } // 调用示例 if (TryGetByInnerKey(InnerKeyTest, out string val, out string outer)) { // 查到了 val }如果你业务上同时知道外层Key内层Key那就不需要遍历直接取值if(AppAttributes.TryGetValue(外层Key,out var innerDic) innerDic.TryGetValue(内层Key,out string val)) { }

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价