我正在尝试创建一个字典列表作为另一个字典的值。
我基本上想要存储这样的数据
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;
}
}
如何在主目录中添加新条目?以及如何访问/更新列表中字典的值?
答案 0 :(得分:2)
字典没有用于插入元素的构造函数。您可以使用集合初始化程序语法:
var entry = new Dictionary<string, int>
{
{ key, value }
};
您的其他问题与Dictionary<string, List<Dictionary<string, int>>>
的事实不符,因为您将其用作Dictionary<string, Dictionary<string, int>>
。
由于您的代码似乎有意义,我建议将您的定义更改为:
Dictionary<string, Dictionary<string, int>> userPrivileges = new Dictionary<string, Dictionary<string, int>>();