public class Node {
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; } // 根節點 ParentId = 0 或 null
public List Children { get; set; } = new List();
}
public List BuildTree(List flatList, int rootPid = 0) {
return flatList
.Where(n => n.ParentId == rootPid)
.Select(n => {
n.Children = BuildTree(flatList, n.Id);
return n;
})
.ToList();
}
// 用法
var allNodes = dbContext.Nodes.ToList(); // 從數據庫讀取
var tree = BuildTree(allNodes);
Dictionary> 映射 ParentId -> 子節點列表,避免重複遍歷列表。將樹序列化為 JSON,綁定至 TreeView、zTree、Element UI Tree 等組件展示。