以前寫代碼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循環來一級推一級,我頭都大了,寫的太麻煩。遞歸雖然很簡單,但是也要花點時間思考。