資料庫儲存無限級分類 (如 `ID, ParentID, Name, Depth`),前端需樹狀顯示。本文提供 C# 完整實作:定義樹節點類別、依 `Depth` 排序讀取資料構建記憶體樹、遞歸輸出 HTML `
public class ZoneList {
private readonly ZoneList _parent;
private readonly List _childs = new List();
private readonly ZoneItem _value;
public ZoneList Parent => _parent;
public List Childs => _childs;
public ZoneItem Value => _value;
public ZoneList Root {
get {
var cur = this;
while (cur.Parent != null) cur = cur.Parent;
return cur;
}
}
public ZoneList() { }
public ZoneList(ZoneItem value, ZoneList parent) { _value = value; _parent = parent; }
public ZoneList AddChild(ZoneItem value) {
var node = new ZoneList(value, this);
_childs.Add(node);
return node;
}
}
public class ZoneItem {
public int ID { get; set; }
public int Tree { get; set; } // Depth/Level
public string Name { get; set; }
}
public ZoneList Select() {
var root = new ZoneList();
ZoneItem item;
int currentDepth = 0;
using (var reader = SiteSQL.ExecuteReader("ZoneSelect")) // SELECT * FROM Zone ORDER BY LID ASC
while (reader.Read()) {
item = new ZoneItem { ID = reader.GetInt32(0), Tree = reader.GetInt32(1), Name = reader.GetString(2) };
int depthDiff = currentDepth - item.Tree;
for (int i = 0; i <= depthDiff; i++) root = root.Parent; // 回溯到父層
root = root.AddChild(item);
currentDepth = item.Tree;
}
return root.Root;
}
關鍵:資料需按「前序遍歷順序」(父節點先於子節點,同層按順序) 排序,`Depth` 遞增表示進入子層,遞減表示返回父層。
private void ZoneOutWrite(ZoneList node) {
foreach (var child in node.Childs) {
Response.Write($"頁面調用:Response.Write(""); ZoneOutWrite(tree.Root); Response.Write("
");
WITH RECURSIVE CTE (SQL 2005+) 直接輸出巢狀 JSON/XML,減少應用層組裝。