标签:递归 PParentId NetCore C# Age Pname PersonModel new ID
1:在实际开发中,我们会经常使用到无限递归的情况,如菜单,父子级等的情况
2:Code
1 using System; 2 using System.Collections.Generic; 3 using ConsoleApp1.Models; 4 using System.Linq; 5 using Newtonsoft.Json; 6 namespace ConsoleApp1 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 var allData = GetListData(); 13 var parentNode = allData.Where(p => p.PParentId == 0).ToList(); 14 List<PersonModel> tree = new List<PersonModel>(); 15 foreach (var item in parentNode) 16 { 17 PersonModel p1 = new PersonModel { Children = new List<PersonModel> { } }; 18 int _id = item.ID; 19 p1.ID = _id; 20 p1.Pname = item.Pname; 21 p1.Age = item.Age; 22 p1.PParentId = item.PParentId; 23 GetNewNodes(allData, p1); 24 tree.Add(p1); 25 } 26 string jsonTree = JsonConvert.SerializeObject(tree, Formatting.Indented); 27 Console.WriteLine(jsonTree); 28 Console.ReadKey(); 29 } 30 31 static void GetNewNodes(List<PersonModel> all, PersonModel curItem) 32 { 33 var subItems = all.Where(c => c.PParentId == curItem.ID).ToList(); 34 curItem.Children = new List<PersonModel>(); 35 curItem.Children.AddRange(subItems); 36 foreach (var subItem in subItems) 37 { 38 GetNewNodes(all, subItem); 39 } 40 } 41 static List<PersonModel> GetListData() 42 { 43 return new List<PersonModel> { 44 new PersonModel{ID=1001,Age=68,Pname="QQ1",PParentId=0 }, 45 new PersonModel{ID=1002,Age=78,Pname="ww",PParentId=0 }, 46 new PersonModel{ID=1003,Age=67,Pname="dd",PParentId=0 }, 47 new PersonModel{ID=1004,Age=88,Pname="ff",PParentId=0 }, 48 49 new PersonModel{ID=1005,Age=18,Pname="gg",PParentId=1001}, 50 new PersonModel{ID=1006,Age=16,Pname="cc",PParentId=1003}, 51 new PersonModel{ID=1007,Age=17,Pname="aa",PParentId=1006}, 52 new PersonModel{ID=1008,Age=19,Pname="tt",PParentId=1007}, 53 new PersonModel{ID=1009,Age=20,Pname="ii",PParentId=1004}, 54 new PersonModel{ID=1010,Age=22,Pname="ggf",PParentId=1003} 55 }; 56 } 57 } 58 }
3:测试ok截图
标签:递归,PParentId,NetCore,C#,Age,Pname,PersonModel,new,ID 来源: https://www.cnblogs.com/Fengge518/p/14733584.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。