我有一个数组,我正在尝试使用脚本创建一个嵌套字典,该脚本将根据数组值自动更新字典
string[,] items = new string[8, 3] {
{ "blue", "one","available" },
{ "blue", "two","available" },
{ "blue", "three","not available" },
{ "black", "six", "not available"},
{ "black", "four","available" },
{ "brown", "one","available" },
{ "brown", "seven","available" },
{ "brown", "six","not available" }
};
所以我期待像这样的输出
[{
"blue": {
"one": {
"available": ["store1 ", "store2 "]
},
"two": {
"available": ["store1 ", "store2 "]
},
"three": {
"not available": ["store1 ", "store2 "]
}
}
}, {
"black": {
"three": {
"not available": ["store1 ", "store2 "]
},
"six": {
"available": ["store1 ", "store2 "]
},
"four": {
"not available": ["store1 ", "store2 "]
}
}
}, {
"brown": {
"one": {
"available": ["store1 ", "store2 "]
},
"seven": {
"availble": ["store1 ", "store2 "]
},
"size": {
"not available": ["store1 ", "store2 "]
}
}
}]
我是c#的新手,如何以上述格式创建嵌套字典?
答案 0 :(得分:0)
[store1,store2]
作为每个元素的默认值:
Dictionary<string, Dictionary<string, Dictionary<string, List<string>>>> dictionaryLevel0 = new Dictionary<string, Dictionary<string, Dictionary<string, List<string>>>>();
string[,] items = new string[8, 3]
{
{"blue", "one", "available"}, {"blue", "two", "available"},
{"blue", "three", "not available"}, {"black", "six", "not available"}, {"black", "four", "available"}, {"brown", "one", "available"}, {"brown", "seven", "available"},
{"brown", "six", "not available"}
};
for (int i = 0; i <= items.GetUpperBound(0); i++)
{
if(!dictionaryLevel0.ContainsKey(items[i, 0]))
dictionaryLevel0.Add(items[i, 0], new Dictionary<string, Dictionary<string, List<string>>>());
var dictionaryLevel1 = dictionaryLevel0[items[i, 0]];
if (!dictionaryLevel1.ContainsKey(items[i, 1]))
dictionaryLevel1.Add(items[i, 1], new Dictionary<string, List<string>>());
var dictionaryLevel2 = dictionaryLevel1[items[i, 1]];
if (!dictionaryLevel2.ContainsKey(items[i, 2]))
dictionaryLevel2.Add(items[i, 2], new List<string> { "store1", "store2"});
}