如何在 C# 中使用 stringbuilder 打印分层信息?

how can I print hierarchical information using stringbuilder in C#?

大家好我是 C# 编程的新手,我想打印一棵树 table 像文本信息

eg:
City
  Munich
  London
Country
  UK
  IND

如何使用 stringbuilder 打印此信息? 它不一定是高端 UI 使用缩进设计一些文本信息。

编辑: 格式中实际期望的信息是:

Patient Name   Test
ABC            Cardiology
                 ECG

并且此信息使用 StringBuilder

在 foreach 循环内迭代

您可以使用换行符 \n 作为换行符,使用 \t 作为制表符。

你也可以使用方法AppendLine而不是使用\n

为了得到你想要的,你会做:

var sb = new System.Text.StringBuilder();
sb.AppendLine("City");
sb.AppendLine("\tMunich");
sb.AppendLine("\tLondon");
sb.AppendLine("Country");
sb.AppendLine("\tUK");
sb.AppendLine("\tIND");
Console.Write(sb);

或者这个:

var sb = new System.Text.StringBuilder();
sb.Append("City\n\tMunich\n\tLondon\nCountry\n\tUK\n\tIND\n");
Console.Write(sb);

一个完整的通用版本就可以了:https://dotnetfiddle.net/qhjCsJ

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

public class Node
{
    public string Text {get;set;}
    public IEnumerable<Node> Children{get;set;}=new List<Node>();
}

public class Program
{
    public static void Main()
    {
        var nodes=new []{
            new Node{
                Text="City",
                Children=new []{
                    new Node{Text="Munich"},
                    new Node{Text="London"},
                }
            },
            new Node{
                Text="Country",
                Children=new []{
                    new Node{Text="UK"},
                    new Node{Text="IND"},
                }
            }
        };

        var sb = new System.Text.StringBuilder();
        foreach(var node in nodes)
            RenderNode(sb, node);
        Console.Write(sb);
    }
    private static void RenderNode(StringBuilder sb, Node node, int indentationLevel = 0){
        sb.AppendLine(new String('\t', indentationLevel) + node.Text);
        foreach(var child in node.Children)
            RenderNode(sb, child, indentationLevel+1);
    }
}