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

如何从IList<IDictionary<string, string>>中按指定键获取对应值?

根据键从IList<IDictionary<string, string>>集合中取值

首先需要修正你示例代码中的问题:接口IList和IDictionary不能直接实例化,得用具体实现类(比如List和Dictionary),修正后的代码如下:

IList<IDictionary<string, string>> listOfDicts = new List<IDictionary<string, string>>
{
    new Dictionary<string, string>
    {
        {"key1", "value1"},
        {"key2", "value2"},
        {"key3", "value3"}
    }
};

下面是几种根据指定键获取对应值的实用方法:

方法1:遍历集合逐个查找(获取所有匹配值)

如果需要收集集合中所有包含目标键的字典对应的值,用遍历最直观:

string targetKey = "key2";
List<string> matchedValues = new List<string>();

foreach (var dict in listOfDicts)
{
    if (dict.ContainsKey(targetKey))
    {
        matchedValues.Add(dict[targetKey]);
    }
}
// 此时matchedValues中会包含所有匹配的value,这里结果是["value2"]

方法2:用LINQ快速获取第一个匹配值

如果只需要集合中第一个包含目标键的字典对应的值,用LINQ可以简化代码:
首先需要引入LINQ命名空间:

using System.Linq;

然后执行查询:

string targetKey = "key2";
string firstMatchedValue = listOfDicts
    .FirstOrDefault(dict => dict.ContainsKey(targetKey))?[targetKey];
// 结果为"value2",如果没有找到匹配的键则返回null

这里的?是空值运算符,避免当没有找到符合条件的字典时抛出空引用异常。

方法3:用LINQ获取所有匹配值

如果想用LINQ一行代码收集所有匹配值:

string targetKey = "key2";
IEnumerable<string> allMatchedValues = listOfDicts
    .Where(dict => dict.ContainsKey(targetKey))
    .Select(dict => dict[targetKey]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:57:08