[英]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我努力了
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?
我该怎么办?
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或使用索引 forloop
foreach (var keyValuePair in myDic)
{
Console.WriteLine(keyValuePair.Key);
for (int i = 0; i < keyValuePair.Value.Count; i++)
{
Console.WriteLine(keyValuePair.Value[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.