我们如何使用递归函数或其他方法在c#中打印n级深层嵌套字典? 字典就像
Dictionary<string,object> myDict;
对象可能是n次字典。 我尝试过这样的事情
foreach (string key in nestedDict.Keys)
{
object nextLevel = nestedDict[key];
if(nextLevel.GetType()== typeof(string))
{
foreach(var val in nestedDict)
{
Debug.Log($" the key is {val.Key}");
Debug.Log($" the value is {val.Value}");
if(val.Value.GetType()== typeof(Dictionary<,>))
{
NestedDictIteration((Dictionary<string, object>)val.Value);
}
}
break;
}
else
NestedDictIteration((Dictionary<string, object>)nextLevel);
}
问候 GM
答案 0 :(得分:3)
编写递归方法非常简单,我添加了一个level
参数只是为了使树显示起来更简单:
static void NestedPrint(Dictionary<string,object> dict, int level = 0)
{
foreach(var item in dict)
{
if(item.Value is Dictionary<string,object> nested)
{
Console.WriteLine($"{new string(' ',level)}{item.Key}:");
NestedPrint(nested,level+1);
}
else
{
Console.WriteLine($"{new string(' ',level)}{item.Key} = {item.Value}");
}
}
}