(一)将数据库存储结构转化为内存树型结构算法
树节点定义public class TNode { public string id { get; set; } public string pid { get; set; } public string name { get; set; } public string flag { get; set; } }
树定义public class Tree { TNode node; public List<Tree> Children { get; set; } }
算法定义public static Tree GetTreeList(List<TNode> data, string pid) { Tree root = new Tree(); List<TNode> item = data.FindAll(t => t.pid == pid); //查找父节点下的所有子节点 if (item.Count == 0) { TNode temp = data.Find(t => t.id == pid); if (temp == null) { root = null;//空树 } else { root.node = temp; } } if (item.Count > 0) { Tree p = new Tree();//当前节点父节点指针 foreach (TNode entity in item) { Tree node = GetTreeList(data, entity.id); TNode pnode = data.Find(x => x.id == node.node.pid); if (pnode != null) { p.node = pnode; p.Children.Add(node); root = p; } else { root = node; } } } return root; }