我无法通过指定值来获取密钥。我能做到这一点的最佳方式是什么?
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;
答案 0 :(得分:18)
FirstOrDefault
的返回值为KeyValuePair<string, List<string>>
,因此要获取密钥,只需使用Key
属性即可。像这样:
var emailAdd = statesToEmailDictionary
.FirstOrDefault(x => x.Value.Contains(state))
.Key;
或者,这是查询语法中的等价物:
var emailAdd =
(from p in statesToEmailDictionary
where p.Value.Contains(state)
select p.Key)
.FirstOrDefault();
答案 1 :(得分:2)
我想你想要:
var emailAdd = statesToEmailDictionary.FirstOrDefault(x => x.Value.Any(y => y.Contains(state))).Key;
答案 2 :(得分:1)
var emailAdd = statesToEmailDictionary
.FirstOrDefault(x => x.Value != null && x.Value.Contains(state))
.Key;
但如果您正在寻找表现,我建议您撤消字典并创建一个<state, email>
字典来完成您正在寻找的内容。
// To handle when it's not in the results
string emailAdd2 = null;
foreach (var kvp in statesToEmailDictionary)
{
if (kvp.Value != null && kvp.Value.Contains(state))
{
emailAdd2 = kvp.Key;
break;
}
}
答案 3 :(得分:1)
此主题中的每个人都没有提到FirstOrDefault
方法只能通过Linq获得:
using System;
using System.Collections.Generic;
// FirstOrDefault is part of the Linq API
using System.Linq;
namespace Foo {
class Program {
static void main (string [] args) {
var d = new Dictionary<string, string> () {
{ "one", "first" },
{ "two", "second" },
{ "three", "third" }
};
Console.WriteLine (d.FirstOrDefault (x => x.Value == "second").Key);
}
}
}
答案 4 :(得分:0)
简单的Linq就是这么做的
Dim mKP = (From mType As KeyValuePair(Of <Key type>, <Value type>) In <Dictionary>
Where mType.Value = <value seeked> Select mType).ToList
If mKP.Count > 0 then
Dim value as <value type> = mKP.First.Value
Dim key as <Key type> = mKP.First.Key
End if
当然,如果存在重复值,则会返回多个KeyValuePair
答案 5 :(得分:0)
var emailAdd = statesToEmailDictionary.First(x=>x.Value.Contains(state)).Key;
答案 6 :(得分:-1)
var temp = statesToEmailDictionary.Where( x => x.Value.Contains(state)).FirstOrDefault();
var emailAdd = temp != null ? temp.Key : string.Empty;