从值获取键 - 字典< string,List< string>>
问题描述:
我无法通过指定值获取密钥。
I am having trouble getting the key by specifying a value. What is the best way I can achieve this?
var st1= new List<string> { "NY", "CT", "ME" };
var st2= new List<string> { "KY", "TN", "SC" };
var st3= new List<string> { "TX", "OK", "MO" };
var statesToEmailDictionary = new Dictionary<string, List<string>>();
statesToEmailDictionary.Add("test1@gmail.com", st1);
statesToEmailDictionary.Add("test2@gmail.com", st2);
statesToEmailDictionary.Add("test3@gmail.com", st3);
var emailAdd = statesToEmailDictionary.FirstOrDefault(x => x.Value.Where(y => y.Contains(state))).Key;
答
FirstOrDefault
将是 KeyValuePair< string, List< string>>
,所以要获取密钥,只需使用 Key
属性。像这样:
The return value from FirstOrDefault
will be a KeyValuePair<string, List<string>>
, so to get the key, simply use the Key
property. Like this:
var emailAdd = statesToEmailDictionary
.FirstOrDefault(x => x.Value.Contains(state))
.Key;
或者,以下是查询语法中的等效内容:
Alternatively, here's the equivalent in query syntax:
var emailAdd =
(from p in statesToEmailDictionary
where p.Value.Contains(state)
select p.Key)
.FirstOrDefault();