var listaFirme = new Dictionary<string, string>
{
{ "foo", "bar" }
};
var matchKey = "foo";
return listaFirme.Where(pair => pair.Key == matchKey).Select(pair => pair.Value).ToString();
我知道密钥是唯一的,所以我想从我的字典中返回一个值。通过密钥从字典中获取单个值
var value = listaFirme[matchKey];
//If you don't know for sure that dictionary contains key
string value;
if(a.TryGetValue(matchKey, out value))
{
/* Code here */
}
至于:在这种情况下,如果你想从索引或TryGetValue
字典访问检索键的值,这是行不通的,因为它返回字符串"System.IEnumerable<String>"
...
'Select'返回一个Ienumerable。也许你应该添加'FirstOrDefault'到Select呼叫。 –
由于您有字典,为什么不使用字典专门提供的方法,例如索引器或'TryGetValue'?您目前的方法失去了使用字典的所有性能优势... –