+-
C# .NetCore简单实现无限递归的功能

1:在实际开发中,我们会经常使用到无限递归的情况,如菜单,父子级等的情况

2:Code

using System;
using System.Collections.Generic;
using ConsoleApp1.Models;
using System.Linq;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var allData = GetListData();
var parentNode = allData.Where(p => p.PParentId == 0).ToList();
List<PersonModel> tree = new List<PersonModel>();
foreach (var item in parentNode)
{
PersonModel p1 = new PersonModel { Children = new List<PersonModel> { } };
int _id = item.ID;
p1.ID = _id;
p1.Pname = item.Pname;
p1.Age = item.Age;
p1.PParentId = item.PParentId;
GetNewNodes(allData, p1);
tree.Add(p1);
}
string jsonTree = JsonConvert.SerializeObject(tree, Formatting.Indented);
Console.WriteLine(jsonTree);
Console.ReadKey();
}

static void GetNewNodes(List<PersonModel> all, PersonModel curItem)
{
var subItems = all.Where(c => c.PParentId == curItem.ID).ToList();
curItem.Children = new List<PersonModel>();
curItem.Children.AddRange(subItems);
foreach (var subItem in subItems)
{
GetNewNodes(all, subItem);
}
}
static List<PersonModel> GetListData()
{
return new List<PersonModel> {
new PersonModel{ID=1001,Age=68,Pname="QQ1",PParentId=0 },
new PersonModel{ID=1002,Age=78,Pname="ww",PParentId=0 },
new PersonModel{ID=1003,Age=67,Pname="dd",PParentId=0 },
new PersonModel{ID=1004,Age=88,Pname="ff",PParentId=0 },

new PersonModel{ID=1005,Age=18,Pname="gg",PParentId=1001},
new PersonModel{ID=1006,Age=16,Pname="cc",PParentId=1003},
new PersonModel{ID=1007,Age=17,Pname="aa",PParentId=1006},
new PersonModel{ID=1008,Age=19,Pname="tt",PParentId=1007},
new PersonModel{ID=1009,Age=20,Pname="ii",PParentId=1004},
new PersonModel{ID=1010,Age=22,Pname="ggf",PParentId=1003}
};
}
}
}

3:测试ok截图