如何在C#中打印N层嵌套Dictionary?含递归实现方案问询
在C#中打印N层嵌套的Dictionary<string, object>
我来帮你搞定嵌套字典的打印问题。先聊聊你现有代码里的几个小问题:
- 在判断值是字符串时,你又重复遍历了整个字典,这会导致输出重复;
- 用
val.Value.GetType() == typeof(Dictionary<,>)判断字典类型不够严谨,泛型类型匹配需要考虑具体的类型参数; - 递归调用的逻辑有点绕,也没做层级区分,打印出来的结构会很乱。
下面给你两种靠谱的实现方式:递归和非递归,都能清晰打印任意深度的嵌套字典。
递归实现(简单直观)
这种方式代码简洁,适合大多数场景,而且通过缩进能清晰区分层级:
public static void PrintNestedDictionary(Dictionary<string, object> dict, int depth = 0) { // 生成当前层级的缩进,让嵌套结构一目了然 string indent = new string('\t', depth); foreach (var keyValuePair in dict) { if (keyValuePair.Value is Dictionary<string, object> nestedDict) { // 遇到嵌套字典,先打印key,再递归处理子字典 Debug.Log($"{indent}Key: {keyValuePair.Key} (嵌套字典)"); PrintNestedDictionary(nestedDict, depth + 1); } else { // 非字典类型直接打印key和对应的值 Debug.Log($"{indent}Key: {keyValuePair.Key}, Value: {keyValuePair.Value}"); } } }
代码说明:
- 用
is关键字直接完成类型判断和转换,比GetType()更简洁安全; - 新增
depth参数控制缩进深度,打印出来的结构层级分明; - 遍历每个键值对,遇到嵌套字典就递归调用,深度加1,否则直接输出内容。
非递归实现(避免栈溢出)
如果你的字典嵌套深度特别大(比如几百层),递归可能会触发栈溢出,这时候可以用栈模拟递归过程:
public static void PrintNestedDictionaryIteratively(Dictionary<string, object> dict) { // 栈中存储当前要处理的字典和对应的层级深度 Stack<(Dictionary<string, object> currentDict, int depth)> processingStack = new Stack<(Dictionary<string, object>, int)>(); processingStack.Push((dict, 0)); while (processingStack.Count > 0) { var (currentDict, depth) = processingStack.Pop(); string indent = new string('\t', depth); foreach (var keyValuePair in currentDict) { if (keyValuePair.Value is Dictionary<string, object> nestedDict) { Debug.Log($"{indent}Key: {keyValuePair.Key} (嵌套字典)"); // 压入栈中等待处理,深度加1 processingStack.Push((nestedDict, depth + 1)); } else { Debug.Log($"{indent}Key: {keyValuePair.Key}, Value: {keyValuePair.Value}"); } } } }
代码说明:
- 用栈保存每一层的字典和深度,完全替代递归调用,避免栈溢出;
- 如果需要保持和递归一样的遍历顺序,可以把栈换成队列(广度优先遍历),或者遍历键值对时倒序压栈。
对你现有代码的修正
如果你想基于自己的代码修改,调整后的版本如下,修复了逻辑问题并加入了层级缩进:
public static void NestedDictIteration(Dictionary<string, object> nestedDict, int depth = 0) { string indent = new string('\t', depth); foreach (var val in nestedDict) { Debug.Log($"{indent}the key is {val.Key}"); if (val.Value is Dictionary<string, object> nextLevel) { Debug.Log($"{indent}the value is a nested dictionary"); NestedDictIteration(nextLevel, depth + 1); } else { Debug.Log($"{indent}the value is {val.Value}"); } } }
内容的提问来源于stack exchange,提问作者muhayyuddin gillani
相关产品推荐
相关产品推荐

