Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get single value from dictionary by key

var listaFirme = new Dictionary<string, string>
{
    { "foo", "bar" }
};

var matchKey = "foo";

return listaFirme.Where(pair => pair.Key == matchKey).Select(pair => pair.Value).ToString();

I know that the keys are unique, so I want to return one value from my Dictionary. In this case it doesn't work, as it returns the string "System.IEnumerable<String>"...

like image 247
S.over17 Avatar asked Jun 03 '26 13:06

S.over17


1 Answers

It really does seem like you're overcomplicating this issue.

You can just use the indexer ([]) of the Dictionary class along with the .ContainsKey() method.

If you use something like this:

string val;
if (myDict.ContainsKey(key))
{
    val = myDict[key];
}
else
{
    Console.WriteLine("Key Not Present");
    return;
}

You should achieve the effect that you want.

like image 187
Persistence Avatar answered Jun 06 '26 03:06

Persistence



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!