2016-05-23 38 views
-1

我有一个数组,我使用的脚本会自动更新,基于阵列的字典试图创建一个嵌套的字典中的值创建从值嵌套的字典在C#中自动

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#如何创建一个以上格式的嵌套字典?

+2

您的输入是如何与你的输出这我不清楚。黑色/三种组合从哪里来? store1和store2从哪里来?请解释您的数据意味着什么。 –

+0

因为我们必须循环这个字符串[,] 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”} } – Mounarajan

+0

“我是c#的新手”在学习漫步之前学习 - 循环遍历,确定外键是否存在于字典中,如果不是,则添加它。确定中间关键字是否存在于外部字典中,如果不存在,则添加它,然后将该值添加到内部集合中。当然,有人会发布一个漂亮的单行Linq答案,但是这真的有什么意义吗? –

回答

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