You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#字典中通过多条件查找指定子键对应的值?

解决方案

你的原代码存在几个核心问题:

  • 原字典的元素是KeyValuePair<string, string[]>,不存在g.Value这类属性,你混淆了字典的结构逻辑
  • Where方法的参数需要是针对集合元素的判断逻辑,直接写c.d && e.f不符合C#语法

针对你的需求,这里提供两种可行的实现方案:

方案1:转换为更易操作的键值对字典(推荐)

原字典的每个值是长度为2的数组,第一个元素是你要的"子键",第二个是"子值",先把这些整理成直接映射的字典,后续操作更高效:

// 初始化你的原始字典
var originalDict = new Dictionary<string, string[]>
{
    {"0", new[] {"a", "b"}},
    {"1", new[] {"c", "d"}},
    {"2", new[] {"e", "f"}},
    {"3", new[] {"g", "h"}}
};

// 转换为子键-子值的直接映射字典
var keyValueMap = originalDict.Values.ToDictionary(arr => arr[0], arr => arr[1]);

// 验证条件并取值
string targetValue = null;
if (keyValueMap.TryGetValue("c", out var cVal) && cVal == "d"
    && keyValueMap.TryGetValue("e", out var eVal) && eVal == "f")
{
    keyValueMap.TryGetValue("g", out targetValue);
}

// 输出结果,此时targetValue为"h"
Console.WriteLine(targetValue);

方案2:直接遍历原字典(无需额外字典)

如果不想创建新字典,可以直接遍历原字典的元素完成条件验证和取值:

var originalDict = new Dictionary<string, string[]>
{
    {"0", new[] {"a", "b"}},
    {"1", new[] {"c", "d"}},
    {"2", new[] {"e", "f"}},
    {"3", new[] {"g", "h"}}
};

// 验证两个条件是否满足
bool isCMatch = originalDict.Values.Any(arr => arr[0] == "c" && arr[1] == "d");
bool isEMatch = originalDict.Values.Any(arr => arr[0] == "e" && arr[1] == "f");

string targetValue = null;
if (isCMatch && isEMatch)
{
    // 找到g对应的子值
    targetValue = originalDict.Values.FirstOrDefault(arr => arr[0] == "g")?[1];
}

内容的提问来源于stack exchange,提问作者user2315104

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:40:13