二维表转树结构
Posted chaeyeon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二维表转树结构相关的知识,希望对你有一定的参考价值。
public class UnitTest1 { [TestMethod] public void TestMethod1() { var nodes = new List<Node>() { new Node { Id = 1, PId = null, Data = "学校"}, new Node { Id = 2, PId = null, Data = "医院" }, new Node { Id = 3, PId = 1, Data = "小学" }, new Node { Id = 4, PId = 3, Data = "一年级" }, new Node { Id = 6, PId = 4, Data = "张三" }, new Node { Id = 5, PId = 2, Data = "浙江附属医院" }, }; ToTree(nodes); } public void ToTree(List<Node> nodes,Node node=null) { if (node == null) { var parents = nodes.FindAll(f => f.PId == null); foreach (var item in parents) { ToTree(nodes,item); } } else if (nodes.Exists(f => f.PId == node.Id)) { var childs = nodes.FindAll(f => f.PId == node.Id); node.Childs = childs; nodes.RemoveAll(a => childs.Contains(a)); foreach (var item in childs) { ToTree(nodes, item); } } } } public class Node { public int? Id { get; set; } public string Data { get; set; } public int? PId { get; set; } public List<Node> Childs { get; set; } }
以上是关于二维表转树结构的主要内容,如果未能解决你的问题,请参考以下文章