TreeNode`1.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. namespace System.Collections
  6. {
  7. public class TreeNode<T>
  8. {
  9. public TreeNode(T value)
  10. {
  11. this._value = value;
  12. }
  13. public TreeNode<T> this[int i]
  14. {
  15. get
  16. {
  17. return this._children[i];
  18. }
  19. }
  20. public TreeNode<T> Parent { get; private set; }
  21. public T Value
  22. {
  23. get
  24. {
  25. return this._value;
  26. }
  27. }
  28. public int ChildCount
  29. {
  30. get
  31. {
  32. return this._children.Count;
  33. }
  34. }
  35. public ReadOnlyCollection<TreeNode<T>> Children
  36. {
  37. get
  38. {
  39. return this._children.AsReadOnly();
  40. }
  41. }
  42. public TreeNode<T> AddChild(T value)
  43. {
  44. TreeNode<T> treeNode = new TreeNode<T>(value)
  45. {
  46. Parent = this
  47. };
  48. this._children.Add(treeNode);
  49. return treeNode;
  50. }
  51. public TreeNode<T>[] AddChildren(params T[] values)
  52. {
  53. return (from v in values
  54. select this.AddChild(v)).ToArray<TreeNode<T>>();
  55. }
  56. public bool RemoveChild(TreeNode<T> node)
  57. {
  58. return this._children.Remove(node);
  59. }
  60. public void ClearChild()
  61. {
  62. this._children.Clear();
  63. }
  64. public void Traverse(Action<T> action)
  65. {
  66. if (action != null && this.Value != null)
  67. {
  68. action(this.Value);
  69. for (int i = 0; i < this._children.Count; i++)
  70. {
  71. TreeNode<T> treeNode = this._children[i];
  72. treeNode.Traverse(action);
  73. }
  74. }
  75. }
  76. public IEnumerable<T> Flatten()
  77. {
  78. return new T[]
  79. {
  80. this.Value
  81. }.Union(this._children.SelectMany((TreeNode<T> x) => x.Flatten()));
  82. }
  83. private readonly T _value;
  84. private readonly List<TreeNode<T>> _children = new List<TreeNode<T>>();
  85. }
  86. }