zoukankan      html  css  js  c++  java
  • 递归算法,如何把list中父子类对象递归成树

    以前写代码for循环写的多,递归除了在大学学习以外,真没怎么用过!

    最近项目中使用到了关于族谱排列的问题,就是怎么把数据库里的多个子父类people对象,在界面中用树的结构展示出来

    假设数据库中people有两个字段分别是ID和 ParentId(当然设计的时候肯定会有familypath,rootID之类的字段,这里为了方便介绍就只用俩字段)

    话不多说直接上代码吧

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication4
    {
        public class TestModel
        {
            public void test()
            {
                #region 添加测试数据
                List<People> listP = new List<People>();
                for (int i = 0; i < 1; i++)
                {
                    listP.Add(new People()
                    {
                        ParentId = 0,
                        id = 1
                    });
                }
                for (int i = 0; i < 2; i++)
                {
                    listP.Add(new People()
                    {
                        ParentId = 1,
                        id = i + 10,
                    });
                }
                for (int i = 0; i < 3; i++)
                {
                    listP.Add(new People()
                    {
                        ParentId = 10,
                        id = i + 100, 
                    });
                }
                for (int i = 0; i < 3; i++)
                {
                    listP.Add(new People()
                    {
                        ParentId = 11,
                        id = i + 100,
                    });
                }
                #endregion 上面是添加测试数据
                
                //查询当前节点下的所有子孙对象
                var currentP = new People();
                currentP.id = 1;
    //递归完成后,此处currentP,就添加好了子孙类节点 Recursion(listP, currentP);

                 //then
                 //展示currentP

    
                
            }
    
            public void Recursion(List<People> list,People p)
            {
    if(list==null||list.count==0)
    {
    return;
    } List
    <People> peoples = new List<People>(); for (int i = 0; i < list.Count; i++) { //递归必须要有跳出节点,此处为了不断向下查找子节点 if (list[i].ParentId == p.id) { peoples.Add(list[i]); p.PeopleList = peoples; Recursion(list, list[i]); } } } } public class People { public List<People> PeopleList; public int ParentId; public int id; } }

    呐,就这么简单,看到同事不断用for循环来一级推一级,我头都大了,写的太麻烦。递归虽然很简单,但是也要花点时间思考。

  • 相关阅读:
    Codeforces 631D Messenger KMP
    Google Codejam 2016 Round1A Problem C BFFs 简单图论
    ACM常用数论知识 总结
    C++ 虚函数表
    HDU 5661 Claris and XOR 贪心
    2013亚洲区域赛长沙站 ZOJ 3732 Graph Reconstruction
    [C++] upper_bound和lower_bound
    2015合肥网络赛 HDU 5489 Removed Interval LIS+线段树(树状数组)
    hdu 3532 Max Angle(atan2的使用)
    poj 1106 Transmitters (计算几何,叉积||极角排序)
  • 原文地址:https://www.cnblogs.com/Llh-Forerer2015/p/10169452.html
Copyright © 2011-2022 走看看