Search code examples
c#dictionarykeytrygetvalue

Get the value of a specific key in a dictionary in C#


I have a dictionary like this:

Dictionary<string, List<string>> mydict = new Dictionary<string, List<string>>();

I have tried:

foreach(var value in mydict.Keys)
{
    List<string> key
    key.Add();
} 

I believe this is not the correct way to get a specific key's value.


Solution

  • You have a Dictionary<string, List<string>>. A dictionary have a key and a value. In your case, the key is a string and the value is a List<string>.

    If you want get the value of a concrete key, you can use:

    myDict.TryGetValue("TheValueToSearch", out List<string> list)
    

    TryGetValue return true when the key is in the dictionary. So you can do:

    if (myDict.TryGetValue("TheValueToSearch", out List<string> list))
    {
        // Do something with your list
    }
    

    You can access directly to the list using myDict["TheValueToSearch"] but you get an exception if the key isn't in the dictionary. You can check if exists using myDict.ContainsKey("TheValueToSearch").

    To iterate all dictionary values:

    foreach(var key in mydict.Keys)
    {
        List<string> values = mydict[key];
        // Do something with values
    } 
    

    Apart from that, in the concrete case of a dictionary having a string as a key, you can use an overloaded constructor if you want that key will be case insensitive:

    new Dictionary<string, List<string>>(StringComparer.CurrentCultureIgnoreCase)