C#递归实现目录树

定义一个经典的目录树类结构的类 


    public class TreeNode
    {
        /// 
        /// 子id
        /// 
        public string Id { get; set; }

        /// 
        /// 父id
        /// 
        public string ParentId { get; set; }

        /// 
        /// 名称
        /// 
        public string Name { get; set; }

        /// 
        /// 子节点
        /// 
        public List Children { get; set; }

        /// 
        /// 无参构造函数
        /// 
        public TreeNode()
        {
            Children = new List();
        }

        /// 
        /// 有参构造函数
        /// 
        /// 子id
        /// 名称
        /// 父id
        public TreeNode(string id, string name, string parentId)
        {
            Id = id;
            Name = name;
            ParentId = parentId;
            Children = new List();
        }

        /// 
        /// 有参构造函数
        /// 
        /// 子id
        /// 名称
        /// 父节点
        public TreeNode(string id, string name, TreeNode parent)
        {
            Id = id;
            Name = name;
            ParentId = parent.Id;
            Children = new List();
        }
    }

 添加初始化数据

 TreeNode treeNode1 = new TreeNode("1", "山东", "0");
                TreeNode treeNode2 = new TreeNode("2", "北京", "0");

                TreeNode treeNode3 = new TreeNode("3", "历下区","1");
                TreeNode treeNode4 = new TreeNode("4", "高新区", "1");
                TreeNode treeNode5 = new TreeNode("5", "历城区", "1");
                TreeNode treeNode6 = new TreeNode("6", "甸柳庄", "1");
                TreeNode treeNode7 = new TreeNode("7", "济南长途汽车站东站", "2");


                TreeNode treeNode8 = new TreeNode("8", "朝阳区", "1");
                TreeNode treeNode9 = new TreeNode("9", "海淀区", "1");
                TreeNode treeNode10 = new TreeNode("10", "金盏乡", "1");


                List list = new List();

                list.Add(treeNode1);
                list.Add(treeNode2);
                list.Add(treeNode3);
                list.Add(treeNode4);
                list.Add(treeNode5);
                list.Add(treeNode6);
                list.Add(treeNode7);
                list.Add(treeNode8);
                list.Add(treeNode9);
                list.Add(treeNode10);
                var resps = new List();

核心方法:

   public   List BulidTreeByRecursive(List treeNodes, string id)
        {

            var tree = treeNodes.Where(x => x.ParentId == id).ToList();             

            for (int i = 0; i < tree.Count; i++)
            {
                tree[i].Children = BulidTreeByRecursive(treeNodes, tree[i].Id);
            }
            return tree;


        }

调用:

    var res = BulidTreeByRecursive(list, "0");

 

你可能感兴趣的:(c#,java,html)