Home > OS >  Loop through a dictionary in C# with a list of values
Loop through a dictionary in C# with a list of values

Time:05-23

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?

CodePudding user response:

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]);
    }
}
  •  Tags:  
  • c#
  • Related