Skip to content

Tutorial1.en

houzkin edited this page Nov 9, 2026 · 5 revisions

Assembling and Converting Tree Structures

The following examples use the classes defined below.

public class NamedNode : GeneralTreeNode<NamedNode> {
    public NamedNode() { }
    public string Name { get; set; }
    public override string ToString() => this.Name;
}
public class NamedLayer {
    public string Name { get; set; }
    public List<NamedLayer> ChildLayers { get; } = new List<NamedLayer>();
	public override string ToString() => this.Name;
}
public class NamedRow {
  public int Id { get; set; }
  public int? ParentId { get; set; }
  public string Name { get; set; }
}	
  • NamedNode: A class representing a tree node. It inherits from GeneralTreeNode, which is defined in this library.
  • NamedLayer: A class representing a hierarchical structure.
  • NamedRow: A class that stores its own ID and its parent's ID.

Assembling a Tree Using the Add Methods

var NodeA = new NamedNode() { Name = "A" };
var NodeB = new NamedNode() { Name = "B" };
var NodeC = new NamedNode() { Name = "C" };
var NodeD = new NamedNode() { Name = "D" };
var NodeE = new NamedNode() { Name = "E" };
var NodeF = new NamedNode() { Name = "F" };

NodeA.AddChild(NodeB).AddChild(NodeC);
NodeB.AddChild(NodeD);
NodeC.AddChild(NodeE);
NodeA.InsertChild(0, NodeF);

Console.WriteLine(NodeA.ToTreeDiagram(x => x.Name));
/*
A
├ F
├ B
│ └ D
└ C
  └ E
*/

Assembling an N-ary Tree

The following code assembles a ternary tree from the elements of a collection.

var nodes = "ABCDEFGH".Select(x=> x.ToString()).AssembleAsNAryTree(3, x => new NamedNode() { Name = x });
Console.WriteLine(nodes.ToTreeDiagram(x => x.Name));
/*
A
├ B
│ ├ E
│ ├ F
│ └ G
├ C
│ └ H
└ D
*/

Assembling a Tree Using NodeIndex

You can assemble a tree with a single root node.
If a node index contains a gap, the node at that index and any subsequent nodes that depend on it are excluded.

var dic = new Dictionary<NodeIndex, string>() {
  [new NodeIndex()] = "A",
  [new NodeIndex(0)] = "B",
  [new NodeIndex(1)] = "C",
  [new NodeIndex(0,0)] = "D",
  [new NodeIndex(1,0,5)] = "E",
  [new NodeIndex(1,8)] = "F",
};
var root1 = dic.AssembleTree(x => new NamedNode() { Name = x });
Console.WriteLine(root1.ToTreeDiagram(x => x.Name));

/* Node "E" is excluded because there is no node corresponding to NodeIndex [1,0].
A
├ B
│ └ D
└ C
  └ F
  */

Nodes are processed and added in level order.
As a result, node F is added as a child of node C, but the final index component is not applied.
If you specify the index when adding a node, an exception is thrown, as shown below.

try {
  var root2 = dic.AssembleTree(x=> new NamedNode() { Name = x.ToString() }, (p, c, i) => p.InsertChild(i,c));
  Console.WriteLine(root2.ToTreeDiagram(x => x.Name));
}catch(ArgumentOutOfRangeException e) {
  Console.WriteLine(e.Message);
}
/* An error occurs when attempting to add node "F" to node "C" with index [8].
Index must be within the bounds of the List. (Parameter 'index')
*/

Assembling a Tree Using NodePath

A tree is assembled from paths and the nodes associated with those paths.
If a path is incomplete, the node at that path and any subsequent nodes that depend on it are excluded.

var dic = new Dictionary<NodePath<string>, NamedNode>() {
  [new NodePath<string>("A")] = new NamedNode() { Name = "A"},
  [new NodePath<string>("A","B")] = new NamedNode() { Name = "B"},
  [new NodePath<string> ("A","C","D")] = new NamedNode() { Name ="D"},
};
var root = dic.AssembleTreeByPath();
Console.WriteLine(root.ToTreeDiagram(x=>x.Name));

/* There is no node corresponding to the node path("A", "C"). 
A
└ B
*/

When assembling a tree from a collection of node paths, you can provide a factory function to create all the nodes. This allows you to assemble the tree by specifying only paths to leaf nodes.

var paths = new List<NodePath<string>>() {
  new NodePath<string>("A","B"),
  new NodePath<string>("A","C","D"),
};
var root1 = paths.AssembleTreeByPath(path => new NamedNode() { Name = path.Last() });
Console.WriteLine(root1.ToTreeDiagram(x => x.Name));
/*
A
├ B
└ C
  └ D
*/

Unlike NodeIndex, NodePath can identify separate trees, allowing you to assemble multiple trees from a single collection.

var paths2 = new List<NodePath<string>>() {
  new NodePath<string>("A"),
  new NodePath<string>("A","B"),
  new NodePath<string>("A","C","D"),
  new NodePath<string>("E","F","G"),
  new NodePath<string>("E","F","H"),
};
var roots = paths2.AssembleForestByPath(path => new NamedNode() { Name = path.Last() });

foreach(var tr in roots) {
  Console.WriteLine(tr.ToTreeDiagram(x => x.Name));
}
/*
A
├ B
└ C
  └ D

E
└ F
  ├ G
  └ H
  */

Assembling Multiple Trees From an Adjacency List

You can assemble a tree structure from an adjacency list by specifying the ID of each item and the ID of its parent.
If the parent ID is null or no item with the specified ID is found, the node becomes a root.

var kernels = new List<NamedRow>() {
  new(){ Id = 0, ParentId = null, Name = "Unix" },
  new(){ Id = 1, ParentId = 0, Name = "SystemV" },
  new(){ Id = 2, ParentId = 0, Name = "BSD" },
  new(){ Id = 3, ParentId = 2, Name = "MacOS" },
  new(){ Id = 4, ParentId = null, Name = "Linux" },
  new(){ Id = 5, ParentId = 4, Name = "zen" },
  new(){ Id = 6, ParentId = 4, Name = "pf" },
};
var kernelRoots = kernels.AssembleForestById(x=>x.Id, x=>x.ParentId, x => new NamedNode() { Name = x.Name });

foreach(var kernel in kernelRoots) {
  Console.WriteLine(kernel.ToTreeDiagram(x => x.Name));
}
/*
Unix
├ SystemV
└ BSD
  └ MacOS

Linux
├ zen
└ pf
*/

Assembling Other Hierarchical Structures (Types That Do Not Implement ITreeNode)

The methods used so far—AssembleAsNAryTree, AssembleTree, AssembleTreeByPath, AssembleForestByPath, and AssembleForestById—can also assemble hierarchical structures whose node types do not implement ITreeNode.

var layer1 = "ABCDEF".ToCharArray()
  .AssembleAsNAryTree(3, x => new NamedLayer() { Name = x.ToString() }, x => x.ChildLayers, (p, c) => p.ChildLayers.Add(c));

PrintHierarchy(layer1);
/*
└ A
 └ B
  └ E
  	└ F
 └ C
 └ D
*/

var layer2 = new Dictionary<NodeIndex, string>() {
  [new NodeIndex(0,1)]="D",
  [new NodeIndex(1)]="C",
  [new NodeIndex(0)]="B",
  [new NodeIndex()]="A",
}.AssembleTree(x => new NamedLayer() { Name = x }, (p, c) => p.ChildLayers.Add(c));

PrintHierarchy(layer2);
/*
└ A
 └ B
 	└ D
 └ C
*/

var layer3 = new List<NodePath<string>>() {
  new NodePath<string>("A","B"),
  new NodePath<string>("A","C","D"),
  new NodePath<string>("E","F","G"),
  new NodePath<string>("E","F","H"),
}.AssembleForestByPath(x => new NamedLayer() { Name = x.Last() }, (p, c) => p.ChildLayers.Add(c));

foreach (var t in layer3) PrintHierarchy(t);
/*
└ A
 └ B
 └ C
  └ D
└ E
 └ F
  └ G
  └ H
*/

var layer4 = new List<NamedRow>() {
  new NamedRow(){ Id = 0, ParentId = null, Name="RedHat"},
  new NamedRow(){ Id = 1, ParentId = 0, Name="Fedora"},
  new NamedRow(){ Id = 2, ParentId = 1, Name="Nobara"},
  new NamedRow(){ Id = 3, ParentId = 0, Name="SentOS"},
  new NamedRow(){ Id = 4, ParentId = null, Name="Arch"},
  new NamedRow(){ Id = 5, ParentId = 4, Name="Manjaro"},
  new NamedRow(){ Id = 6, ParentId = null, Name="Debian"},
  new NamedRow(){ Id = 7, ParentId = 6, Name="Ubuntu"},
  new NamedRow(){ Id = 8, ParentId = 7, Name="Mint"},
  new NamedRow(){ Id = 9, ParentId = 7, Name="ZorinOS"},

}.AssembleForestById(x => x.Id, x => x.ParentId, x => new NamedLayer() { Name = x.Name }, (p, c) => p.ChildLayers.Add(c));

foreach (var t in layer4) PrintHierarchy(t);
/*
└ RedHat
   └ Fedora
     └ Nobara
   └ SentOS
└ Arch
   └ Manjaro
└ Debian
   └ Ubuntu
     └ Mint
     └ ZorinOS
*/

Converting Between Tree Structures and Other Hierarchical Structures

The Convert method converts a tree structure into another tree structure or a different hierarchical structure (one whose node type does not implement ITreeNode). To convert a different hierarchical structure into a tree structure, you must first wrap it in ReadOnlyValuedTreeNode, a lightweight wrapper node.
The following code converts NamedNode → NamedLayer → ReadOnlyValuedTreeNode → NamedNode.

var root = new List<NodePath<string>>() {
  new NodePath<string>("A","B"),
  new NodePath<string>("A","C","D"),
}.AssembleTreeByPath(x => new NamedNode() { Name = x.Last() });
Console.WriteLine(root.ToTreeDiagram(x => x.Name));
/*
A
├ B
└ C
  └ D
*/

// NamedNode -> NamedLayer
var layer = root.Convert(x => new NamedLayer() { Name = x.Name.ToLower() }, (p, c) => p.ChildLayers.Add(c));
PrintHierarchy(layer);
/*
└ a
  └ b
  └ c
  	└ d
*/

// NamedLayer -> ReadOnlyValuedTreeNode<NamedLayer,NamedLayer>
var valuedTreeRoot = layer.AsValuedTreeNode(x => x.ChildLayers, x => x);
Console.WriteLine(valuedTreeRoot.ToTreeDiagram(wrapper => wrapper.Value.Name));
/*
a
├ b
└ c
  └ d
*/

// ReadOnlyValuedTreeNode -> NamedNode
var root2 = valuedTreeRoot.Convert(x => new NamedNode() { Name = x.Value.Name.ToUpper() });
Console.WriteLine(root2.ToTreeDiagram(node => node.Name));
/*
A
├ B
└ C
  └ D
*/

Converting a Tree to a Dictionary

The tree is converted into a Dictionary<NodeIndex, T> using NodeIndex as the key.

var t = "ABCDEFG".ToCharArray().AssembleAsNAryTree(2, x => new NamedNode() { Name = x.ToString() });
Console.WriteLine(t.ToTreeDiagram(x=> x.Name));
/*
A
├ B
│ ├ D
│ └ E
└ C
  ├ F
  └ G
  */

var dic = t.ToNodeMap(x => x.Name);
foreach(var pair in dic) {
  Console.WriteLine($"key:{pair.Key},value:{pair.Value}");
}
/*
key:[],value:A
key:[0],value:B
key:[1],value:C
key:[0,0],value:D
key:[0,1],value:E
key:[1,0],value:F
key:[1,1],value:G
  */

Serialization and Deserialization

Although TreeNode instances can be serialized directly, this is not recommended.
If you override SetupChildCollection to initialize the child collection, deserialization may produce an unintended structure.
Therefore, convert each node into a serialization-friendly object before serializing it.

Serializing and Deserializing a Single Tree

This approach preserves the hierarchical structure during serialization.

string path = "Text1.xml";
var root = new List<NodePath<string>>() {
  new("A","B","C"),
  new("A","D","E"),
}.AssembleForestByPath(x => new NamedNode() { Name = x.Last() }).Single();

// Serialize
var sLayer = root.Convert(x => new NamedLayer() { Name = x.Name }, (p, c) => p.ChildLayers.Add(c));
var serializer = new XmlSerializer(typeof(NamedLayer));
using(var sw = new StreamWriter(path)) {
  serializer.Serialize(sw, sLayer);
}
/*
<?xml version="1.0" encoding="utf-8"?>
<NamedLayer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>A</Name>
  <ChildLayers>
  <NamedLayer>
    <Name>B</Name>
    <ChildLayers>
    <NamedLayer>
      <Name>C</Name>
      <ChildLayers />
    </NamedLayer>
    </ChildLayers>
  </NamedLayer>
  <NamedLayer>
    <Name>D</Name>
    <ChildLayers>
    <NamedLayer>
      <Name>E</Name>
      <ChildLayers />
    </NamedLayer>
    </ChildLayers>
  </NamedLayer>
  </ChildLayers>
</NamedLayer>
*/

// Deserialize
NamedLayer layer;
using(StreamReader sr = new StreamReader(path)) {
  layer = (NamedLayer)serializer.Deserialize(sr);
}
var root2 = layer.AsValuedTreeNode(x => x.ChildLayers, x => x)
  .Convert(x => new NamedNode() { Name = x.Value.Name});
Console.WriteLine(root2.ToTreeDiagram(x => x.Name));
/*
A
├ B
│ └ C
└ D
  └ E
  */

Flattening, Serializing, and Deserializing a Single Tree

Convert the tree into a serializable dictionary representation, then serialize and deserialize it.

string path = "Text2.xml";
var root = new List<NodePath<string>>() {
  new("A", "B", "C"),
  new("A", "D", "E"),
  new("A", "D", "F", "G"),
}.AssembleForestByPath(x => new NamedNode() { Name = x.Last() }).Single();

// Serialize
var serializable = root.ToSerializableNodeMap(x => x.Name);
var serializer = new XmlSerializer(typeof(SerializableNodeMap<string>));
using (StreamWriter fs = new StreamWriter(path)) {
  serializer.Serialize(fs, serializable);
}
/*
<?xml version="1.0" encoding="utf-8"?>
<SerializableNodeMapOfString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[]</NodeIndex>
  </Key>
  <Value>A</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[0]</NodeIndex>
  </Key>
  <Value>B</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[1]</NodeIndex>
  </Key>
  <Value>D</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[0,0]</NodeIndex>
  </Key>
  <Value>C</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[1,0]</NodeIndex>
  </Key>
  <Value>E</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[1,1]</NodeIndex>
  </Key>
  <Value>F</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
  <KeyValueItemOfNodeIndexCodeOfStringString>
  <Key>
    <NodeIndex>[1,1,0]</NodeIndex>
  </Key>
  <Value>G</Value>
  </KeyValueItemOfNodeIndexCodeOfStringString>
</SerializableNodeMapOfString>
  */

// Deserialize
SerializableNodeMap<string> snm;
using (StreamReader sr = new StreamReader(path)) {
  snm =(SerializableNodeMap<string>)serializer.Deserialize(sr);
}
var root2 = snm.AssembleTree(x=> new NamedNode() { Name = x});
Console.WriteLine(root2.ToTreeDiagram(x => x.Name));
/*
A
├ B
│ └ C
└ D
  ├ E
  └ F
  └ G
  */

Flattening, Serializing, and Deserializing Multiple Trees

Assign an ID and a parent ID to each item, then serialize and deserialize the collection as an adjacency list.

string path = "Text3.xml";
var forest1 = new List<NodePath<string>>() {
  new("A", "B", "C"),
  new("A", "B", "D"),
  new("E", "F", "G"),
}.AssembleForestByPath(x => new NamedNode() { Name = x.Last() });

// Assign ID and ParentID to each row.
var adjList = forest1.Select(x => x.AsValuedTreeNode(a => new NamedRow() { Name = a.Name })).ToArray();
foreach (var pair in adjList.SelectMany(x => x.LevelOrder()).Select((x, i) => (Row: x, Index: i))) {
  pair.Row.Value.Id = pair.Index;
  pair.Row.Value.ParentId = pair.Row.Parent?.Value.Id;
}

// Serialize
var rows1 = adjList.SelectMany(x => x.LevelOrder()).Select(x => x.Value).ToList();
var serializer = new XmlSerializer(typeof(List<NamedRow>));
using (var sw = new StreamWriter(path)) {
  serializer.Serialize(sw, rows1);
}
/*
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfNamedRow xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <NamedRow>
  <Id>0</Id>
  <ParentId xsi:nil="true" />
  <Name>A</Name>
  </NamedRow>
  <NamedRow>
  <Id>1</Id>
  <ParentId>0</ParentId>
  <Name>B</Name>
  </NamedRow>
  <NamedRow>
  <Id>2</Id>
  <ParentId>1</ParentId>
  <Name>C</Name>
  </NamedRow>
  <NamedRow>
  <Id>3</Id>
  <ParentId>1</ParentId>
  <Name>D</Name>
  </NamedRow>
  <NamedRow>
  <Id>4</Id>
  <ParentId xsi:nil="true" />
  <Name>E</Name>
  </NamedRow>
  <NamedRow>
  <Id>5</Id>
  <ParentId>4</ParentId>
  <Name>F</Name>
  </NamedRow>
  <NamedRow>
  <Id>6</Id>
  <ParentId>5</ParentId>
  <Name>G</Name>
  </NamedRow>
</ArrayOfNamedRow>
  */

// Deserialize
List<NamedRow> rows2;
using (StreamReader sr = new StreamReader(path)) {
  rows2 = (List<NamedRow>)serializer.Deserialize(sr);
}
var forest2 = rows2.AssembleForestById(x => x.Id, x => x.ParentId, x => new NamedNode() { Name = x.Name });
foreach (var t in forest2) Console.WriteLine(t.ToTreeDiagram(x => x.Name));
/*
A
└ B
  ├ C
  └ D

E
└ F
  └ G
*/

Clone this wiki locally