递归

一,递归

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<menu> data = new List<menu>();
            data.Add(new menu() { Id = 1, Pid = 0, Name = "广东省" });
            data.Add(new menu() { Id = 2, Pid = 1, Name = "珠海市" });
            data.Add(new menu() { Id = 3, Pid = 2, Name = "斗门区" });
            data.Add(new menu() { Id = 4, Pid = 2, Name = "香洲区" });
            data.Add(new menu() { Id = 5, Pid = 2, Name = "保税区" });
            data.Add(new menu() { Id = 6, Pid = 1, Name = "广州" });
            data.Add(new menu() { Id = 7, Pid = 6, Name = "天河区" });
            data.Add(new menu() { Id = 8, Pid = 6, Name = "越秀区" });
            data.Add(new menu() { Id = 9, Pid = 7, Name = "棠下" });
            data.Add(new menu() { Id = 10, Pid = 7, Name = "棠东" });
            data.Add(new menu() { Id = 11, Pid = 3, Name = "白蕉镇" });
            data.Add(new menu() { Id = 12, Pid = 3, Name = "井岸镇" });
            data.Add(new menu() { Id = 13, Pid = 0, Name = "广西省" });
            var ss = Dg(data, 0);
        }
        public static List<menu> Dg(List<menu> data, int ParentId)
        {
            List<menu> list = data.Where(m => m.Pid == ParentId).ToList<menu>();
            List<menu> total = new List<menu>();
            foreach (var item in list)
            {
                item.MenuList = Dg(data, item.Id);
                total.Add(item);
            }
            return total;
        }
    }
    public class menu
    {
        public int Id { get; set; }
        public int Pid { get; set; }
        public string Name { get; set; }
        public List<menu> MenuList { get; set; }
    }
}

递归的思路,在一个集合中,将当前相同的父节点筛选出来保存在集合中menuList中,
然后这就是一个完整的节点,然而当menuList集合的各个节点中如果还存在子节点,
就需要遍历当前的menuList获取到menuList节点的id为父节点,然后再获取子集合,
这时就是递归的思路

posted @ 2018-12-14 17:04  叶丶梓轩  阅读(158)  评论(0编辑  收藏  举报