3

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

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?

2
  • 1
    How many List items are you thinking there are in the Dictionary for Key1 and Key2? For those two items, I only see one item in each of them. Perhaps your test/sample data is setup incorrectly with missing double-quotes ? Commented May 22, 2022 at 19:22
  • I have several List items.. You're right, the double quotes are missing. I will correct that, thanks Commented May 22, 2022 at 19:37

1 Answer 1

2

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.