【根节点】C#找树形数据的根节点Id

科室类

    public class Dept
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string ParentId { get; set; }
        public string RootId { get; set; }
    }

测试代码

        static void Test07()
        {
            List<Dept> depts = new List<Dept>();
            depts.Add(new Dept { Id = "01", Name = "部门01", ParentId = "", RootId = "", });
            depts.Add(new Dept { Id = "02", Name = "部门02", ParentId = "", RootId = "", });
            depts.Add(new Dept { Id = "03", Name = "部门03", ParentId = "01", RootId = "", });
            depts.Add(new Dept { Id = "04", Name = "部门04", ParentId = "01", RootId = "", });
            depts.Add(new Dept { Id = "05", Name = "部门05", ParentId = "04", RootId = "", });
            depts.Add(new Dept { Id = "06", Name = "部门06", ParentId = "05", RootId = "", });

            foreach (var dept in depts)
            {
                if (string.IsNullOrEmpty(dept.ParentId))
                {
                    dept.RootId = dept.Id;
                }
                else
                {
                    dept.RootId = FindRootId(depts, dept);
                }
            }

            // 输出结果,查看RootId的赋值情况
            foreach (var dept in depts)
            {
                Console.WriteLine($"Id: {dept.Id}, Name: {dept.Name}, ParentId: {dept.ParentId}, RootId: {dept.RootId}");
            }
        }

        private static string FindRootId(List<Dept> depts, Dept currentDept)
        {
            string parentId = currentDept.ParentId;
            while (!string.IsNullOrEmpty(parentId))
            {
                var parentDept = depts.Find(d => d.Id == parentId);
                if (string.IsNullOrEmpty(parentDept.ParentId))
                {
                    return parentDept.Id;
                }
                parentId = parentDept.ParentId;
            }
            return currentDept.Id; // 如果没有找到父部门,则返回自身Id
        }

运行结果

Id: 01, Name: 部门01, ParentId: , RootId: 01
Id: 02, Name: 部门02, ParentId: , RootId: 02
Id: 03, Name: 部门03, ParentId: 01, RootId: 01
Id: 04, Name: 部门04, ParentId: 01, RootId: 01
Id: 05, Name: 部门05, ParentId: 04, RootId: 01
Id: 06, Name: 部门06, ParentId: 05, RootId: 01
ok
posted @ 2025-04-13 23:58  我有我奥妙  阅读(8)  评论(0)    收藏  举报