AllTreeData.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections.Generic;
  2. using System.Runtime.Serialization;
  3. namespace Tree
  4. {
  5. [DataContract]
  6. public class AllTreeData
  7. {
  8. private readonly List<TreeNodeData> treeNodeDatas = new List<TreeNodeData>();
  9. public int MaxNodeId { get; set; }
  10. public int MaxTreeId { get; set; }
  11. [DataMember(Order = 1)]
  12. public List<TreeNodeData> TreeNodeDatas
  13. {
  14. get
  15. {
  16. return this.treeNodeDatas;
  17. }
  18. }
  19. private readonly Dictionary<int, TreeNodeData> allTreeNodes =
  20. new Dictionary<int, TreeNodeData>();
  21. /// <summary>
  22. /// tree对应的root id
  23. /// </summary>
  24. private readonly Dictionary<int, int> treeRootId = new Dictionary<int, int>();
  25. public void Init()
  26. {
  27. this.MaxNodeId = 0;
  28. this.MaxTreeId = 0;
  29. foreach (TreeNodeData nodeData in this.treeNodeDatas)
  30. {
  31. this.allTreeNodes[nodeData.Id] = nodeData;
  32. if (nodeData.Id > this.MaxNodeId)
  33. {
  34. this.MaxNodeId = nodeData.Id;
  35. }
  36. if (nodeData.TreeId > this.MaxTreeId)
  37. {
  38. this.MaxTreeId = nodeData.TreeId;
  39. }
  40. if (nodeData.Parent == 0)
  41. {
  42. this.treeRootId[nodeData.TreeId] = nodeData.Id;
  43. }
  44. }
  45. }
  46. public void Save()
  47. {
  48. treeNodeDatas.Clear();
  49. foreach (KeyValuePair<int, TreeNodeData> pair in allTreeNodes)
  50. {
  51. treeNodeDatas.Add(pair.Value);
  52. }
  53. }
  54. /// <summary>
  55. /// 删除一棵树的所有节点
  56. /// </summary>
  57. /// <param name="treeId"></param>
  58. public void Remove(int treeId)
  59. {
  60. var removeList = new List<int>();
  61. foreach (int key in this.allTreeNodes.Keys)
  62. {
  63. TreeNodeData nodeData = allTreeNodes[key];
  64. if (nodeData.TreeId != treeId)
  65. {
  66. continue;
  67. }
  68. removeList.Add(key);
  69. }
  70. foreach (int key in removeList)
  71. {
  72. this.allTreeNodes.Remove(key);
  73. }
  74. Save();
  75. }
  76. public TreeNodeData this[int id]
  77. {
  78. get
  79. {
  80. return this.allTreeNodes[id];
  81. }
  82. }
  83. }
  84. }