-
Notifications
You must be signed in to change notification settings - Fork 3
/
TreeNodeCollection.cs
122 lines (74 loc) · 2.75 KB
/
TreeNodeCollection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Gsemac.Collections {
public class TreeNodeCollection<T> :
ICollection<ITreeNode<T>> {
// Public members
public int Count => nodes.Count;
public bool IsReadOnly => false;
public TreeNodeCollection() {
}
public TreeNodeCollection(ITreeNode<T> parentNode) {
this.parentNode = parentNode;
}
public void Add(ITreeNode<T> item) {
nodes.Add(GetUnderlyingNode(item));
}
public void Add(T item) {
Add(new TreeNode<T>(item));
}
public void Clear() {
nodes.Clear();
}
public bool Contains(ITreeNode<T> item) {
return nodes.Contains(GetUnderlyingNode(item));
}
public void CopyTo(ITreeNode<T>[] array, int arrayIndex) {
nodes.CopyTo(array, arrayIndex);
}
public IEnumerator<ITreeNode<T>> GetEnumerator() {
IEnumerable<ITreeNode<T>> result;
if (parentNode != null)
result = nodes.Select(node => new NodeWrapper(node, parentNode));
else
result = nodes;
return nodes.GetEnumerator();
}
public bool Remove(ITreeNode<T> item) {
return nodes.Remove(GetUnderlyingNode(item));
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
// Private members
private class NodeWrapper :
ITreeNode<T> {
// Public members
public ITreeNode<T> Parent { get; }
public int Level { get; }
public ICollection<ITreeNode<T>> Children => underlyingNode.Children;
public T Value => underlyingNode.Value;
ITreeNode ITreeNode.Parent => Parent;
IEnumerable<ITreeNode> ITreeNode.Children => Children;
public NodeWrapper(ITreeNode<T> underlyingNode, ITreeNode<T> parentNode) {
Parent = parentNode;
Level = parentNode.Level + 1;
this.underlyingNode = underlyingNode;
}
public ITreeNode<T> GetUnderlyingNode() {
return underlyingNode;
}
// Private members
private readonly ITreeNode<T> underlyingNode;
}
private readonly ITreeNode<T> parentNode;
private readonly IList<ITreeNode<T>> nodes = new List<ITreeNode<T>>();
private ITreeNode<T> GetUnderlyingNode(ITreeNode<T> node) {
if (node.GetUnderlyingNode() is null)
return node;
else
return GetUnderlyingNode(node.GetUnderlyingNode());
}
}
}