如何在C#中打印n级(深度)嵌套词典

时间:2020-03-09 11:12:13

标签: c#

我们如何使用递归函数或其他方法在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

1 个答案:

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

实时示例:https://dotnetfiddle.net/hAdDZw