c# - 从值为 List<string> 的字符串中获取键

标签 c# list dictionary key

我有一个字典,其中键是字符串,值是字符串列表。

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>() {
    {"alpha", new List<string> {"one", "two", "three"}}
    {"beta", new List<string> {"four", "five", "six"}}
    {"gamma", new List<string> {"seven", "eight", "nine"}}
}

有没有办法在给定值中存在的字符串时返回键?

例如,给定"four",返回"beta"

我找到了类似 this 的内容, 但只有当值是单个值而不是列表时它才有效,我不知道如何使用列表来做到这一点。

谢谢。

最佳答案

按值搜索字典效率不高,但是:

string firstKey = dict.Where(kv => kv.Value.Contains("four"))
    .Select(kv => kv.Key)
    .FirstOrDefault(); // returns null if no list contains "four"

或者如果没有列表包含给定值,您可以提供默认键,然后使用 First 是安全的:

string firstKey = dict.Where(kv => kv.Value.Contains("foo"))
    .Select(kv => kv.Key)
    .DefaultIfEmpty("--no value found--")
    .First(); // result: "--no value found--"

关于c# - 从值为 List<string> 的字符串中获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954921/

相关文章:

c# - ASP .NET 中的首选验证

c# - 通过检查元素的条件将列表拆分为子列表

python - 如何将两个列表合并为一个,同时更改某些值?

c# - 在特定位置添加字典元素

python - 用另一个字典中的键替换字典的值

c# - 不指定参数的函数字典

C# |检查按钮点击的计时器

c# - Response.TransmitFile() 的替代品

python - 将多个视频文件中的抓取帧追加到列表列表中

c# - 添加对象到 ObservableCollection 列表对象