简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM