Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建字典列表作为另一个字典的值?_C#_Asp.net_Dictionary - Fatal编程技术网

C# 如何创建字典列表作为另一个字典的值?

C# 如何创建字典列表作为另一个字典的值?,c#,asp.net,dictionary,C#,Asp.net,Dictionary,我正在尝试创建一个字典列表,作为另一个字典的值 我基本上希望像这样存储数据 userPrivileges ["foo"]["a"] = 4; userPrivileges ["foo"]["b"] = 8; userPrivileges ["foo"]["c"] = 16; userPrivileges ["bar"]["a"] = 4; 这是我试过的 Dictionary<string, List<Dictionary<string, int>>> use

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

我基本上希望像这样存储数据

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>>>();
Dictionary userPrivileges=newdictionary();
要添加或更新字典列表中的键,我使用以下方法

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

}
受保护的void AddOrUpdateUserPrivilege(字符串moduleName、字符串键、int值)
{
如果(!this.userPrivileges.ContainsKey(moduleName))
{
var条目=新字典(键、值);
this.userPrivileges.Add(moduleName,条目);
} 
其他的
{
this.userPrivileges[moduleName][key]|=值;
}
}
下面是语法错误的屏幕截图


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

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

var entry = new Dictionary<string, int> 
{
    { key, value }
};
var entry=新字典
{
{键,值}
};
您的其他问题与您有一本
词典
,这一事实不符,因为您将其用作
词典

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

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

非常感谢您在这方面的帮助。在用您的建议更新代码之后,它以不同的方式修复了语法错误。但是当我运行它时,我得到了以下错误
在mscorlib.dll中发生了“System.Collections.Generic.KeyNotFoundException”类型的异常,但没有在用户代码中处理其他信息:给定的密钥在字典中不存在。
错误指向这一行
this.userPrivileges[moduleName][key]|=value
@MikeA发生这种情况是因为您的字典中不存在
key
。您还需要检查
是否(userPrivileges[moduleName].ContainsKey(key))
正确!非常感谢你的帮助:)@MikeA不用担心,伙计:)