【问题标题】:How can I create a list of dictionaries as value of another dictionary?如何创建一个字典列表作为另一个字典的值?
【发布时间】:2016-10-05 12:07:18
【问题描述】:

我正在尝试创建一个字典列表作为另一个字典的值。

我基本上是想这样存储数据

userPrivileges ["foo"]["a"] = 4;
userPrivileges ["foo"]["b"] = 8;
userPrivileges ["foo"]["c"] = 16;
userPrivileges ["bar"]["a"] = 4;

这是我尝试过的

Dictionary<string, List<Dictionary<string, int>>> userPrivileges = new Dictionary<string, List<Dictionary<string, int>>>();

要添加或更新字典列表中的键,我使用以下方法

protected void AddOrUpdateUserPrivilege(string moduleName, string key, int value)
{
    if (!this.userPrivileges.ContainsKey(moduleName))
    {
        var entry = new Dictionary<string, int>(key, value);

        this.userPrivileges.Add(moduleName, entry);
    } 
    else
    {
        this.userPrivileges[moduleName][key] |= value;
    }

}

这里是语法错误的截图

如何向主目录添加新条目?以及如何访问/更新列表中字典的值?

【问题讨论】:

    标签: c# asp.net dictionary


    【解决方案1】:

    字典没有用于插入元素的构造函数。您可以使用集合初始值设定项语法:

    var entry = new Dictionary<string, int> 
    {
        { key, value }
    };
    

    您的其他问题与您拥有Dictionary&lt;string, List&lt;Dictionary&lt;string, int&gt;&gt;&gt; 的事实不符,因为您将其用作Dictionary&lt;string, Dictionary&lt;string, int&gt;&gt;。

    由于您的代码似乎与后者一样有意义,我建议您将定义更改为:

    Dictionary<string, Dictionary<string, int>> userPrivileges = new Dictionary<string, Dictionary<string, int>>();
    

    【讨论】:

    • 非常感谢您在这方面的帮助。在用您的建议更新代码后,它以不同的方式修复了语法错误。但是当我运行它时,我收到以下错误An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll but was not handled in user code Additional information: The given key was not present in the dictionary. 错误指向这一行this.userPrivileges[moduleName][key] |= value;
    • @MikeA 发生这种情况是因为您的字典中不存在key。您还需要查看if (userPrivileges[moduleName].ContainsKey(key))
    • 对!非常感谢您的帮助:)
    • @MikeA 别担心队友:)
    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 2021-03-09
    • 2019-05-04
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2014-08-15
    相关资源
    最近更新 更多