私はJavaでコードを書いていましたが、C#コードを書くのは問題ではないと思います。私のコードhereをテストすることができます。アイデアは、結果セットを次のクラスで表される階層にマップすることです。
Nodeクラス:
class Node {
private String name;
private List<Node> children;
Node(String name) {
this.name = name;
children = new ArrayList<>();
}
void addChild(Node child) {
children.add(child);
}
List<Node> getChildren() {
return children;
}
public String toString() {
return this.name;
}
}
いくつかのヘルパークラスだけできれいなコードのために:
class Tag {
private String open;
private String close;
Tag(String open, String close) {
this.open = open;
this.close = close;
}
String open() {
return open;
}
String close() {
return close;
}
}
階層エミュレーション(私もデモのために追加のレベルを追加しました):
private static List<Node> createHierarchy() {
List<Node> nodes = new ArrayList<>();
Node nodeA = new Node("A");
Node nodeB = new Node("B");
Node nodeC = new Node("C");
Node nodeD = new Node("D");
Node nodeE = new Node("E");
Node nodeF = new Node("F");
Node nodeG = new Node("G");
Node node1 = new Node("1");
Node node2 = new Node("2");
Node node3 = new Node("3");
Node node4 = new Node("4");
nodeA.addChild(nodeB);
nodeA.addChild(nodeC);
nodeD.addChild(node1);
nodeD.addChild(node2);
node2.addChild(node3);
node2.addChild(node4);
nodeA.addChild(nodeD);
nodeA.addChild(nodeE);
nodes.add(nodeA);
nodes.add(nodeF);
nodes.add(nodeG);
return nodes;
}
そしてメインロジック。
public static void main(String[] args) {
printHierarchy(createHierarchy(), new StringBuilder());
}
private static void printHierarchy(List<Node> nodes, StringBuilder stringBuilder) {
stringBuilder.append(ul.open());
for (Node node : nodes) {
printNode(node, stringBuilder);
printChildren(node.getChildren(), stringBuilder);
stringBuilder.append(li.close());
}
stringBuilder.append(ul.close());
System.out.print(stringBuilder.toString());
}
private static void printNode(Node node, StringBuilder stringBuilder) {
stringBuilder.append(li.open()).append(node);
}
private static void printChildren(List<Node> children, StringBuilder stringBuilder) {
if (children.size() == 0) {
return;
}
stringBuilder.append(ul.open());
for (Node child : children) {
stringBuilder.append(li.open()).append(child);
if (child.getChildren().size() > 0) {
printChildren(child.getChildren(), stringBuilder);
}
stringBuilder.append(li.close());
}
stringBuilder.append(ul.close());
}
結果:
<ul>
<li>A
<ul>
<li>B</li>
<li>C</li>
<li>D
<ul>
<li>1</li>
<li>2
<ul>
<li>3</li>
<li>4</li>
</ul>
</li>
</ul>
</li>
<li>E</li>
</ul>
</li>
<li>F</li>
<li>G</li>
</ul>
私は私のデータ構造をトラバースする再帰を使用しました