C#树状结构

简单的组织架构,树状结构示例

  1. 新建一个控制台程序
  2. 创建一个类作为Model ,Rank
//Rank Model
public class Rank
    {     
        public string SysId { get; set; }
        public string HrParentId { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        //必需
        public List Children { get; set; }
    }
  1. 再创建一个类TreeNode

1.给Model造一些假数据

public List source = new List()
         {
            new Rank(){SysId = "1", HrParentId = "0"},
            new Rank(){SysId = "2", HrParentId = "0"},
            new Rank(){SysId = "3", HrParentId = "0"},
            new Rank(){SysId = "4", HrParentId = "1"},
            new Rank(){SysId = "5", HrParentId = "1"},
            new Rank(){SysId = "6", HrParentId = "1"},
            new Rank(){SysId = "7", HrParentId = "3"},
            new Rank(){SysId = "8", HrParentId = "3"}
         };

2.创建方法进行递归,在这里需要说明一下,一定要写递归的出口,就是程序结束的条件,不然无限循环,难搞哦,此处是foreach循环没数据就下一步了

public List GetTreeNode(bool b,string parentId)
        {
            if (b)
            {
                source.Add(new Rank() { SysId = "0", HrParentId = "-1", Name = "集团" });
            }
            //1找到一级父亲
            var parents = source.FindAll(p => p.HrParentId == parentId);
            //2给一级父元素递归赋值子元素
            foreach (var item in parents)
            {
                item.Children = ConvertToChild(source, item.SysId);
            }
            return parents;
        }

        private List ConvertToChild(List source,string parentId)
        {
            var parents = source.FindAll(p => p.HrParentId == parentId);
            foreach (var item in parents)
            {
                item.Children = ConvertToChild(source, item.SysId);
            }
            return parents;
        }
  1. 控制台调用,加断点调试
class Program
    {
        static void Main(string[] args)
        {
            TreeNode t = new TreeNode();
            var res = t.GetTreeNode(true,"0");
            //Hello World!
            Console.WriteLine("Hello World!");
        }
    }

C#树状结构_第1张图片
OK,一个简单的树状结构就完成了,希望对你能有所帮助,加油!

你可能感兴趣的:(asp.net)