码迷,mamicode.com
首页 > 其他好文 > 详细

二维表转树结构

时间:2019-03-29 18:57:12      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:set   str   span   div   test   get   style   reac   ==   

 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; }
    }

 

二维表转树结构

标签:set   str   span   div   test   get   style   reac   ==   

原文地址:https://www.cnblogs.com/chaeyeon/p/10623088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!