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

Loop through a dictionary in C# with a list of values

I have a dictionary

public Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>(2)
{
    {"Key1", new List<string> {"Val1", "Val2", "Val3"} },
    {"Key2", new List<string> {"Val4", "Val5"} }
};

I want to loop through the keys with the count of values for each key.

I have tried

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

foreach (string key in myDic.Keys)
{
    for (int i = 0; i < myDic.Values.Count; i++)
    {
        //do something
    }
}

which is obviously not working but I can’t think of a better way.

//do something has to be executed for the keys a specific number of times as per the number of values. How can I go about this?

>Solution :

you can do something like with out testing it.

foreach (var keyValuePair in myDic)
{
    Console.WriteLine(keyValuePair.Key);
    foreach (var s in keyValuePair.Value)
    {
        Console.WriteLine(s);
    }
}

Or with index forloop

foreach (var keyValuePair in myDic)
{
    Console.WriteLine(keyValuePair.Key);
    for (int i = 0; i < keyValuePair.Value.Count; i++)
    {
        Console.WriteLine(keyValuePair.Value[i]);
    }
}
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