我创建了一个复杂的字典。
mainDict<mainKey, SubDict>
subDict<subKey, sub1Dict>
sub1Dict<sub1Key, sub2Dict>
sub2Dict<sub2Key, sub2Value>
.......
如何将其打印出来(基于vs2005&amp; .net 2.0)
mainKey/subKey/sub1Key/sub2Key, sub2Value
我是否需要将mainDict转换为List并调用join()?
谢谢。答案 0 :(得分:3)
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<mainKey, SubDict> pair1 in mainDict)
foreach (KeyValuePair<subKey, sub1Dict> pair2 in pair1.Value)
foreach (KeyValuePair<sub1Key, sub2Dict> pair3 in pair2.Value)
foreach (KeyValuePair<sub2Key, sub2Value> pair4 in pair3.Value)
{
sb.AppendFormat("{0}/{1}/{2}/{3}, {4}",
pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair4.Value);
}
更新:
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, object> pair1 in mainDict)
foreach (KeyValuePair<string, object> pair2 in (Dictionary<string, object>)pair1.Value)
foreach (KeyValuePair<string, object> pair3 in (Dictionary<string, object>)pair2.Value)
foreach (KeyValuePair<string, object> pair4 in (Dictionary<string, object>)pair3.Value)
{
sb.AppendFormat("{0}/{1}/{2}/{3}, {4}",
pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair4.Value);
}
答案 1 :(得分:2)
看不到比嵌套循环更好的东西 - 遍历mainDict的键,然后是subDict的键,依此类推。然后,您可以将循环变量和最内层值呈现为字符串。
答案 2 :(得分:2)
您可以使用LINQ:
var qry = from pair1 in mainDict
from pair2 in pair1.Value
from pair3 in pair2.Value
from pair4 in pair3.Value
select pair1.Key + "/" + pair2.Key + "/" + pair3.Key
+ "/" + pair4.Key + ", " + pair4.Value;
foreach(var s in qry) Console.WriteLine(s);
答案 3 :(得分:0)
我最后写了几分钟,试着在这里找到一个。我们走了:
//---------------------------------------------------
// Get a nested Dictionary, then...
Console.WriteLine(DictionaryPrint(nestedDictionary));
//---------------------------------------------------
private static string DictionaryPrint(Dictionary<object,object> dictionary, string space = "")
{
string output = "";
foreach(KeyValuePair<object,object> entry in dictionary)
{
output += space + entry.Key + ": ";
if (entry.Value is Dictionary<object, object>)
output += "\n" + DictionaryPrint((Dictionary<object, object>)entry.Value, space + " ");
else if (entry.Value is List<object>)
output += "\n" + ListPrint((List<object>)entry.Value, space + " ");
else
output += entry.Value + "\n";
}
return output;
}
private static string ListPrint(List<object> list, string space = "")
{
string output = "";
foreach (object entry in list)
{
if (entry is List<object>)
output += ListPrint((List<object>)entry, space + " ");
else if (entry is Dictionary<object, object>)
output += DictionaryPrint((Dictionary<object, object>)entry, space + " ");
else
output += entry + "\n";
}
return output;
}
答案 4 :(得分:0)
如果你碰巧使用JSON,你可能会比
更糟糕JsonConvert.SerializeObject(yourDict, Formatting.Indented);