如何在C#中将值插入多层词典?

时间:2020-10-22 07:50:36

标签: c# dictionary

我必须写个字典

Dictionary<int, Dictionary<string, string>> dictionary = new Dictionary<int, Dictionary<string, string>>() { };

所以稍后我将检查并获取类似的值

if (dictionary[index].key* == value) { stuff; }    //*or maybe it's [index][key], that's not the matter

我只是不知道和不知道如何在字典中写各种元素(我已经在这里和在线搜索过),正确的语法,我尝试的任何内容都会出错。希望您能提供帮助,谢谢您!

4 个答案:

答案 0 :(得分:0)

要插入该对象,请执行以下操作:

Dictionary<int, Dictionary<string, string>> dictionary = new Dictionary<int, Dictionary<string, string>>() { };

您需要多次插入。像这样:

//create the first level and instanciate a new dictionary object
dictionary.Add(1234, new Dictionary<string, string>());
//insert into the dictionary created above
dictionary[1234].Add("test", "test");

dictionary[1234]返回一个Dictionary<string, string>,其中1234是在dictionary.Add(1234, new Dictionary<string, string>());

中添加的密钥

答案 1 :(得分:0)

index这个名称确实不合适,因为字典不使用索引,而是使用键。

但是,要添加新的子词典:

dictionary[i] = new Dictionary<string, string>();

要添加/替换现有子词典中的值,请执行以下操作:

dictionary[i][key] = value;

如果您想在创建或未创建子词典时安全地插入新值,则可以创建扩展方法:

public static void Insert(this Dictionary<int, Dictionary<string, string>> dict, int i, string key, string value)
{
    if (!dict.ContainsKey(i)) dict[i] = new Dictionary<string, string>();
    dict[i][key] = value;
}

然后这样使用:

dictionary.Insert(1, "SomeKey", "SomeValue");

请注意,如果多次插入相同的键,这将覆盖子词典中的键。

答案 2 :(得分:0)

如何使用collection initialisers?如果您希望字典包含常量值,那么这很好:

var dictionary = new Dictionary<int, Dictionary<string, string>>() { 
    [111] = new Dictionary<string, string> {
        ["nested key1"] = "value 1",
        ["nested key2"] = "value 2",
        ["nested key3"] = "value 3",
        ["nested key4"] = "value 4",
    },
    [222] = new Dictionary<string, string> {
        ["nested key5"] = "value 5",
        ["nested key6"] = "value 6",
        ["nested key7"] = "value 7",
        ["nested key8"] = "value 8",
    },
};

答案 3 :(得分:-1)

dictionary的类型为Dictionary<int, Dictionary<string, string>>,因此var b = dictionary[3]的类型为Dictionary<string, string>,要获取b的条目,请使用语法b["Hello"]来获取string
如果要在一个子句中编写它们,请使用(dictionary[3])["Hello"]。由于operator[]是左关联的,因此(dictionary[3])["Hello"]可以写为dictionary[3]["Hello"]

相关问题