We have a case where we have a hierarchical tree structure and we need to get the 'branch' of any particular node. The structure is a one-way linked-list from the child to the parent, but we want to define the branch in the direction from parent to child.
Here's an over-simplified example of the implementation we came up with. Just wondering if there's a better/more effective way to achieve this given those constraints. Just feels verbose to me to do it this way.
#nullable enable
public class Node {
public Node(String name, Node? parent)
=> (Name, Parent) = (name, parent);
public string Name { get; set; }
public Node? Parent { get; init; }
IEnumerable<Node> GetBranch(){
static IEnumerable<Node> getBranchReversed(Node? node) {
while (node is not null) {
yield return node;
node = node.Parent;
}
}
return getBranchReversed(this).Reverse();
}
}
Only other way I can think of is to accumulate into a list where I insert into the first position, then just return the list (typing this from my memory so it may not compile...)
ReadOnlyCollection<Node> GetBranch(){
Node? node = this;
var branch = new List<Node>();
while (node is not null) {
branch.insert(0, node);
node = node.Parent;
}
return branch.AsReadOnly();
}
Again, just wondering if there's any other way to achieve this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…