【问题标题】:Pretty printing a collection recursively漂亮地递归打印集合
【发布时间】:2019-09-08 00:12:00
【问题描述】:

我已经看到很多关于这个的问题,但我还没有看到任何关于递归执行的问题。我创建了一些扩展方法,它们在深度为 1 时可以很好地进行漂亮的打印。它看起来像这样:

    public static string PrettyToString<K, V>(this Dictionary<K, V> dictionary)
    {
        string result = "{";
        foreach (var kvp in dictionary)
        {
            result += $"({kvp.Key}, {kvp.Value}) ";
        }
        result += "}";
        return result;
    }

    public static string PrettyToString<T>(this List<T> list)
    {
        string result = "{";
        foreach (var element in list)
        {
            result += $"{element}, ";
        }
        result += "}";
        return result;
    }

    public static string PrettyToString<T>(this T [] list)
    {
        string result = "{";
        foreach (var element in list)
        {
            result += $"{element}, ";
        }
        result += "}";
        return result;
    }

但是,如果 K、V 或 T 是另一个集合,如 List 或 Dictionary?我想递归漂亮地打印,但我不知道该怎么做。结果,我的输出如下所示:

{(foo, System.Collections.Generic.Dictionary`2[System.String,System.Boolean])...

我希望它看起来像这样:

    {(foo, {(bar, true)})...

我正在寻找无论嵌套类型如何都可以递归打印的方法:

var x = new List<Dictionary<string, string>>();
var y = new Dictionary<Dictionary<string, string>, string>>();
var z = new Dictionary<Dictionary<string, string>, List<string>>>();
...
x.PrettyToString();
y.PrettyToString();
z.PrettyToString();

应该全部递归打印出内容。我如何做到这一点?

【问题讨论】:

  • 您的第二个方法可以更改为接受IEnumerable&lt;T&gt;,而无需修改方法的主体,允许它支持其他集合类型,例如T[] 和HashSet。这样可以摆脱多余的第三种方法。
  • @Amy 谢谢你的提示 :)

标签: c#


【解决方案1】:

我更改了您的方法的签名并使其成为非泛型。

诀窍是在转换之前确定类型。

请看下面的示例代码。希望对你有帮助。

请看源码底部的Ext类。

Try it online

using System;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            var Dic = new Dictionary<int, string> { { 1, "Ali" }, { 2, "B" } };
            Console.WriteLine(Dic.PrettyToString());

            var Dic1 = new Dictionary<string, float> { { "Ali", 12.5f }, { "B", 99.9f } };
            Console.WriteLine(Dic1.PrettyToString());

            var Dic2 = new Dictionary<List<int>, string>
            {
                { new List<int> { 1, 2, 3 }, "A" },
                { new List<int> { 4, 5, 6 }, "B" }
            };
            Console.WriteLine(Dic2.PrettyToString());

            var Dic3 = new Dictionary<Dictionary<string, string>, string>
            {
                { new Dictionary<string, string> { { "a", "A" }, { "b", "B" } }, "Capital" },
                { new Dictionary<string, string> { { "1", "1" }, { "2", "4" }, { "4", "16" } }, "Power" }
            };
            Console.WriteLine(Dic3.PrettyToString());

            var Dic4 = new Dictionary<Dictionary<string, string>, List<string>>
            {
                { new Dictionary<string, string> { { "a", "A" }, { "b", "B" } }, new List<string> { "A", "B" } },
                { new Dictionary<string, string> { { "1", "1" }, { "2", "4" }, { "4", "16" } }, new List<string> { "1", "2", "4" } }
            };
            Console.WriteLine(Dic4.PrettyToString());

            var L = new List<List<int>>
            {
                new List<int> { 1, 2, 3 },
                new List<int> { 4, 5, 6 }
            };
            Console.WriteLine(L.PrettyToString());

            Console.ReadKey();
        }
    }

    static class Ext
    {
        public static string PrettyToString(this IDictionary dictionary)
        {
            string result = "{";
            foreach (var Key in dictionary.Keys)
            {
                result += string.Format("({0}, {1}) ", PrettyToString(Key), PrettyToString(dictionary[Key]));
            }
            result += "}";
            return result;
        }

        public static string PrettyToString(this IEnumerable list)
        {
            string result = "{";
            foreach (var element in list)
            {
                result += string.Format("{0}, ", PrettyToString(element));
            }
            result += "}";
            return result;
        }

        private static string PrettyToString(object O)
        {
            var S = O as string;
            if (S != null) return S;

            var D = O as IDictionary;
            if (D != null) return D.PrettyToString();

            var L = O as IEnumerable;
            if (L != null) return L.PrettyToString();

            return O.ToString();
        }
    }
}

【讨论】:

  • 感谢任何反对投票的评论!
  • 我没有对你投反对票,但这段代码无法在我的编辑器中编译。这可能就是你被否决的原因。
  • 我使用了 C# 7 模式匹配功能。我认为这就是您收到编译错误的原因。请尝试更新的示例代码。此外,还有一个链接到 .NET fiddle 在线编辑器,它工作正常。
  • 我的错误出现在 PrettyToString 签名上。例如,它说我需要字典的类型参数。更新:啊!我需要使用System.Collections 而不是System.Collections.Generic。直到现在我才意识到其中的区别。
  • 你太棒了!谢谢:D
猜你喜欢
  • 2014-06-28
  • 2010-09-28
  • 2013-02-16
  • 2017-09-25
  • 1970-01-01
  • 2015-01-22
  • 2017-05-26
  • 2010-12-06
  • 2017-12-19
相关资源
最近更新 更多