S.o*_*r17 0 c# linq dictionary
var listaFirme = new Dictionary<string, string>
{
{ "foo", "bar" }
};
var matchKey = "foo";
return listaFirme.Where(pair => pair.Key == matchKey).Select(pair => pair.Value).ToString();
Run Code Online (Sandbox Code Playgroud)
我知道键是唯一的,所以我想从我的字典中返回一个值.在这种情况下,它不起作用,因为它返回字符串"System.IEnumerable<String>"...
Gil*_*een 10
如果要从索引器的字典访问中检索键的值,或者TryGetValue:
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 */
}
Run Code Online (Sandbox Code Playgroud)
至于为什么你得到了你做的结果是:LINQ的操作Where和Select返回一个IEnumerable<T>这样做的时候ToString就可以了它执行ToString的IEnumerable是打印出来的类型.
请注意,这listaFirme不是一个好名字dictionary
如果您没有字典并且想要返回一个项目,那么您将使用FirstOrDefault:
var value = someList.FirstOrDefault(item => /* some predicate */)?.Value;
Run Code Online (Sandbox Code Playgroud)
看起来你似乎过于复杂了这个问题.
你可以只使用索引([]中的)Dictionary类与一起.ContainsKey()的方法.
如果你使用这样的东西:
string value;
if (myDict.ContainsKey(key))
{
value = myDict[key];
}
else
{
Console.WriteLine("Key Not Present");
return;
}
Run Code Online (Sandbox Code Playgroud)
你应该达到你想要的效果.