c# - 使用值列表循环遍历 C# 中的字典

标签 c#

我有一本字典

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"} }
};

我想使用每个键的值计数遍历键。

我试过了

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

这显然行不通,但我想不出更好的方法。

//必须根据值的数量对键执行特定次数的操作。我该怎么做?

最佳答案

你可以在不测试的情况下做类似的事情。

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

或者用索引forloop

foreach (var keyValuePair in myDic)
{
    Console.WriteLine(keyValuePair.Key);
    for (int i = 0; i < keyValuePair.Value.Count; i++)
    {
        Console.WriteLine(keyValuePair.Value[i]);
    }
}

关于c# - 使用值列表循环遍历 C# 中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72340578/

相关文章:

c# - 一定秒数后出现空引用异常

javascript - 金特 "unexpected reserved word"

C#构造函数

c# - C# 桌面应用程序的数据库引擎

c# - 在 ASP.NET Core 中模拟 User.Identity 以进行单元测试

c# - 为什么这个 linq 查询只返回第一个属性?

c# - 流畅的 NHibernate 映射 : one-to-one (or none)

c# - 如何在 WPF 中使用鼠标在 ViewPort3D 中旋转相机?

c# - 使用 HttpClient 的进度信息

c# - 如何设置 Outlook 文件夹的自定义图标?