public class NodeList : List<Node> {
}
public class Node {
public string Name { get; set; }
public NodeList Children { get; set; }
}
public class Repository {
public static NodeList GetNodes() {
return new NodeList {
new Node { Name = "1",
Children = new NodeList {
new Node { Name = "1.1" },
new Node { Name = "1.2",
Children = new NodeList {
new Node { Name = "1.2.1" }
}
},
new Node { Name = "1.3" },
new Node { Name = "1.4" },
}
},
new Node { Name = "2",
Children = new NodeList {
new Node { Name = "2.1" }
}
},
new Node { Name = "3" }
};
}
}
The Recursive Function
12345678910111213141516171819202122
<%
Action<NodeList, int> printNodesRecursively = null;
printNodesRecursively = (NodeList nodeList, int depth) => {
if (nodeList==null || nodeList.Count==0) return;
%>
<ul class="node-list depth-<%=depth%>">
<%
foreach (Node node in nodeList) {
%>
<li>
<%=node.Name%>
<%printNodesRecursively(node.Children, depth + 1);%>
</li>
<%
}
%>
</ul>
<%
};
NodeList nodes = Repository.GetNodes(); // Or ViewData use for ASP.NET MVC
printNodesRecursively(nodes, 0);
%>
Notice: The printNodesRecursively function is declared with the value of null at first. Otherwise, the compiler says that the inner printNodesRecursively call is made on an unassigned variable.
This will basically print a
with an for each node, and inside each , another
with its children, recursively.
Notice the extra ”depth” which indicates the current depth level in the tree inside the printNodesRecursively function. In this example it adds a special class to each level.