我有一个字典,其中键是字符串,值是字符串列表。
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/