C# 递归获取树形结构数据类型

Model:可嵌套子类

    public class Equipment
    {
        public string Name { get; set; }             
        public Guid Id { get; set; }             
        public Guid ParentId { get; set; }             
        public List<Equipment> Children { get; set; }             
    }

 

        //递归获取子级
        static List<Equipment> GetChildren(Equipment equipment,List<Equipment> list)
        {
            if (!list.Any(a => a.ParentId == equipment.Id))
                return null;
            else
            {
                equipment.Children = list.Where(a=>a.ParentId == equipment.Id).ToList();
                foreach (var item in equipment.Children)
                {
                    item.Children = GetChildren(item, list);
                }
                return equipment.Children;
            }
        }

        static void Main(string[] args)
        {
            var list = new List<Equipment>();
            var e1 = new Equipment { Id = Guid.NewGuid(), ParentId = Guid.Empty, Name = "一级" };
            var e2 = new Equipment { Id = Guid.NewGuid(), ParentId = e1.Id, Name = "二级" };
            var e3 = new Equipment { Id = Guid.NewGuid(), ParentId = e2.Id, Name = "三级" };
            list.Add(e1);
            list.Add(e2);
            list.Add(e3);
            //对list 做树型结构处理
            //第一级
            var result = list.Where(a =>!list.Any(b=>a.ParentId==b.Id)).ToList();
            foreach (var item in result)
            {
                item.Children = GetChildren(item, list);
            }
            //result 树形结构完成
            Console.ReadKey();
        }

 

posted @ 2023-12-13 10:07  点终将连成线  阅读(156)  评论(0编辑  收藏  举报