I was looking for a tree or graph data structure in C# but I guess there isn't one provided. An Extensive Examination of Data Structures Using C# 2.0 explains a bit about why. Is there a convenient library which is commonly used to provide this functionality? Perhaps through a strategy pattern to solve the issues presented in the article.
I feel a bit silly implementing my own tree, just as I would implementing my own ArrayList.
I just want a generic tree which can be unbalanced. Think of a directory tree. C5 looks nifty, but their tree structures seem to be implemented as balanced red-black trees better suited to search than representing a hierarchy of nodes.
Here's a Tree
You can even use initializers:
I hate to admit it but I ended up writing my own tree class using a linked list. On an unrelated note I just discovered this round thing which, when attached to a thing I'm calling an 'axle' allows for easier transportation of goods.
Because it isn't mentioned I would like you draw attention the now released .net code-base: specifically the code for a
SortedSet
that implements a Red-Black-Tree:https://github.com/Microsoft/referencesource/blob/master/System/compmod/system/collections/generic/sortedset.cs
This is, however, a balanced tree structure. So my answer is more a reference to what I believe is the only native tree-structure in the .net core library.
Here's my own:
Output:
Yet another tree structure:
Sample usage:
BONUS
See fully-fledged tree with:
https://github.com/gt4dev/yet-another-tree-structure
I create a Node class that could be helpfull for other people. The class has properties like:
There is also the possibility to convert a flat list of items with an Id and a ParentId to a tree. The nodes holds a reference to both the children and the parent, so that makes iterating nodes quite fast.