fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. var fileMenu = new Tree<string>("File")
  10. .AddChild("Open")
  11. .AddChild("Edit")
  12. .AddChild(
  13. new Tree<string>("Recent Files")
  14. .AddChild("foo.txt")
  15. .AddChild("bar.txt"))
  16. .AddChild("Exit");
  17. Console.WriteLine(fileMenu.ToString());
  18. }
  19.  
  20. class Tree<T>
  21. {
  22. private readonly T value;
  23. private readonly List<Tree<T>> children = new List<Tree<T>>();
  24.  
  25. public Tree(T value)
  26. {
  27. this.value = value;
  28. }
  29.  
  30. public IEnumerable<Tree<T>> Children
  31. {
  32. get { return this.children; }
  33. }
  34.  
  35. public T Value
  36. {
  37. get { return this.value; }
  38. }
  39.  
  40. public Tree<T> AddChild(Tree<T> tree)
  41. {
  42. this.children.Add(tree);
  43. return this;
  44. }
  45.  
  46. public Tree<T> AddChild(T value)
  47. {
  48. return this.AddChild(new Tree<T>(value));
  49. }
  50.  
  51. public override string ToString()
  52. {
  53. var sb = new StringBuilder();
  54. ToStringHelper(sb, 1);
  55. return sb.ToString();
  56. }
  57.  
  58. private void ToStringHelper(StringBuilder sb, int depth)
  59. {
  60. sb.AppendLine(this.value.ToString());
  61. foreach (var child in this.children)
  62. {
  63. sb.Append('-', depth);
  64. child.ToStringHelper(sb, depth + 1);
  65. }
  66. }
  67. }
  68. }
Success #stdin #stdout 0.03s 24160KB
stdin
Standard input is empty
stdout
File
-Open
-Edit
-Recent Files
--foo.txt
--bar.txt
-Exit