Home > OS >  get a value of a specific key in a dictionary in C#
get a value of a specific key in a dictionary in C#

Time:07-07

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 wrong to get a specific key value

CodePudding user response:

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)
  • Related