场景说明
结构:Dictionary<string, Dictionary<string, 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 -> 对应值 Dictionary<string, string> matchResult = new Dictionary<string, 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); } } }方式3:LINQ 简写版本
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快速索引,必须遍历所有外层字典。
如果查询频繁,建议额外建立反向索引:
Dictionary<string, 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)) { }