递归算法,如何把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循环来一级推一级,我头都大了,写的太麻烦。递归虽然很简单,但是也要花点时间思考。

 

posted @ 2018-12-24 16:46  forever2015  阅读(2618)  评论(0编辑  收藏  举报