I'm banging my head on the desk for hours now, but it seems like I'm too stupid to implement a tree structure in C#.
- There are 2 types of nodes, I call them
NodeandNodeCollection. - Both
NodeandNodeCollectioncan have a parentNodeCollection - A
NodeCollectioncan have a collection of child nodes, which are eitherNodeorNodeCollection - A
Nodecannot have any childs. - A
NodeorNodeCollectionwithout parent is considered to be the root node A
Nodehas a value of any arbitary type, done with generics- NodeCollection
- NodeCollection
- Node
- Node
- NodeCollection
- Node
- NodeCollection
- Node
- Node
- NodeCollection
- Node
- NodeCollection
- NodeCollection
Is there a collection type from the BCL that serves this purpose? What I have so far:
public abstract class NodeBase {
protected NodeCollection Parent { get; set; }
}
public class Node<T> : NodeBase {
public string Key { get; set; }
public T Value { get; set; }
}
public class NodeCollection : NodeBase {
public ICollection<NodeBase> Children { get; set; }
}
This solution 'works', however I cannot just walk down the tree as NodeBase doesn't offer any childreen. I have to validate the type to find out if the child node is a NodeCollection, but if it is not, I can't properly cast the Node because it might be of unknown type.