-
Notifications
You must be signed in to change notification settings - Fork 1
/
IChild.cs
77 lines (70 loc) · 1.82 KB
/
IChild.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
namespace Open.Hierarchy;
/// <summary>
/// Represents something that has a parent (<see cref="IChild.Parent"/>).
/// </summary>
public interface IChild
{
/// <summary>
/// The parent of this child.
/// </summary>
object? Parent { get; }
}
/// <summary>
/// Represents something that has a parent (<see cref="IChild{TParent}.Parent"/>).
/// </summary>
/// <typeparam name="TParent"></typeparam>
public interface IChild<out TParent> : IChild
where TParent : class
{
/// <summary>
/// The generic parent of this child.
/// </summary>
new TParent? Parent { get; }
}
/// <summary>
/// Extensions for getting ancestors.
/// </summary>
public static class ChildExtensions
{
/// <summary>
/// Crawls the ancestor lineage and returns them.
/// </summary>
/// <typeparam name="TNode">The node type.</typeparam>
/// <param name="node">The child node to use.</param>
/// <returns>An enumerable of the ancestors.</returns>
public static IEnumerable<TNode> GetAncestors<TNode>(
this TNode node)
where TNode : class, IChild<TNode>
{
return node is null
? throw new ArgumentNullException(nameof(node))
: GetAncestorsCore(node);
static IEnumerable<TNode> GetAncestorsCore(TNode node)
{
TNode? parent;
while ((parent = node.Parent) is not null)
{
yield return parent;
node = parent;
}
}
}
/// <summary>
/// Crawls the ancestor lineage returns the first node with no parent.
/// </summary>
/// <typeparam name="TNode">The node type.</typeparam>
/// <param name="node">The child node to start with.</param>
/// <returns>The root node.</returns>
public static TNode GetRoot<TNode>(
this TNode node)
where TNode : class, IChild<TNode>
{
if (node is null) throw new ArgumentNullException(nameof(node));
TNode? parent;
while ((parent = node.Parent) != null)
{
node = parent;
}
return node;
}
}