コード例 #1
0
 public void AddChild(IndentTreeNode child)
 {
     if (child != null)
     {
         Children.Add(child);
     }
 }
コード例 #2
0
 private static void doDump(IndentTreeNode treeNode, StringBuilder sb, string indent)
 {
     sb.AppendLine(indent + treeNode.Text);
     foreach (var child in treeNode.Children)
     {
         doDump(child, sb, indent + @"    ");
     }
 }
コード例 #3
0
        // https://stackoverflow.com/questions/21735468/parse-indented-text-tree-in-java

        public static List <IndentTreeNode> Parse(IEnumerable <string> lines, int rootDepth = 0, char indentChar = '\t')
        {
            var roots = new List <IndentTreeNode>();

            IndentTreeNode prev = null;

            foreach (var line in lines)
            {
                if (string.IsNullOrEmpty(line.Trim(indentChar)))
                {
                    continue;
                }
                //throw new Exception(@"Empty lines are not allowed.");

                var currentDepth = countWhiteSpacesAtBeginningOfLine(line, indentChar);

                if (currentDepth == rootDepth)
                {
                    var root = new IndentTreeNode(line, rootDepth);
                    prev = root;

                    roots.Add(root);
                }
                else
                {
                    if (prev == null)
                    {
                        throw new Exception(@"Unexpected indention.");
                    }
                    if (currentDepth > prev.Depth + 1)
                    {
                        throw new Exception(@"Unexpected indention (children were skipped).");
                    }

                    if (currentDepth > prev.Depth)
                    {
                        var node = new IndentTreeNode(line.Trim(), currentDepth, prev);
                        prev.AddChild(node);

                        prev = node;
                    }
                    else if (currentDepth == prev.Depth)
                    {
                        var node = new IndentTreeNode(line.Trim(), currentDepth, prev.Parent);
                        prev.Parent.AddChild(node);

                        prev = node;
                    }
                    else
                    {
                        while (currentDepth < prev.Depth)
                        {
                            prev = prev.Parent;
                        }

                        // at this point, (currentDepth == prev.Depth) = true
                        var node = new IndentTreeNode(line.Trim(indentChar), currentDepth, prev.Parent);
                        prev.Parent.AddChild(node);
                    }
                }
            }
            return(roots);
        }
コード例 #4
0
 public IndentTreeNode(string text, int depth = 0, IndentTreeNode parent = null)
 {
     Text   = text;
     Depth  = depth;
     Parent = parent;
 }