Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading