gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:31:10 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com