• 递归


    一,递归

    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为父节点,然后再获取子集合,
    这时就是递归的思路

  • 相关阅读:
    大厂Redis高并发场景设计,面试问的都在这!
    POJ1006——中国剩余定理
    HDU3501——欧拉函数裸题
    堆-动态的排序(洛谷1801-黑匣子)
    图中欧拉回路数量
    ip地址
    网络通信概述
    网络通信概述
    软件安装与卸载
    软件安装与卸载
  • 原文地址:https://www.cnblogs.com/May-day/p/10120449.html
Copyright © 2020-2023  润新知