Get single value from dictionary by key

60,176

Solution 1

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 value;
if (myDict.ContainsKey(key))
{
    value = myDict[key];
}
else
{
    Console.WriteLine("Key Not Present");
    return;
}

You should achieve the effect that you want.

Solution 2

If you want to retrieve a value of a key from a dictionary access by indexer or 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 */
}

As for why you got the result you did: Linq operations of Where and Select return an IEnumerable<T> so when doing ToString on it it executes the ToString of IEnumerable which is to print it's type.

Notice that listaFirme isn't a good name for a dictionary


If you did not have a dictionary and wanted to return one item then you'd use FirstOrDefault:

var value = someList.FirstOrDefault(item => /* some predicate */)?.Value;

Solution 3

It seems that you've overcomplicated the usage. In this case you don't need Linq. Just use the Dictionary provided indexer: listaFirme[matchKey]. This returns the related value. IF the key does not exist the Dictionary throws a KeyNotFoundException exception. If you want to check if the key exists you can use the ContainsKey() method which returns a bool.

Share:
60,176
S.over17
Author by

S.over17

Updated on October 08, 2020

Comments

  • S.over17
    S.over17 over 3 years
    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>"...