Search code examples
c#stringbuilder

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


Hi guys I am new to C# programming and I wanted to print a tree table like textual information

eg:
City
  Munich
  London
Country
  UK
  IND

how can I print this information using the stringbuilder? it need not be a high end UI design just some textual information using indentation.

Edit: The information actually expected in the format is:

Patient Name   Test
ABC            Cardiology
                 ECG

and this information is iterated inside a foreach loop using StringBuilder


Solution

  • you can use the escape caracters \n for the new line, and \t for the tab.

    You can also use the method AppendLine not to use the \n.

    To get what you want, you would do:

    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);
    

    or this:

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

    a complete generic version does the trick: 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);
        }
    }