之前寫代碼for循環寫的多,遞歸除了在大學學習之外,真沒怎麼用過!數據庫
最近項目中使用到了關於族譜排列的問題,就是怎麼把數據庫裏的多個子父類people對象,在界面中用樹的結構展現出來學習
假設數據庫中people有兩個字段分別是ID和 ParentId(固然設計的時候確定會有familypath,rootID之類的字段,這裏爲了方便介紹就只用倆字段)測試
話很少說直接上代碼吧spa
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循環來一級推一級,我頭都大了,寫的太麻煩。遞歸雖然很簡單,可是也要花點時間思考。code