數(shù)據(jù)表中有字段ID,fatherID即可存儲一個樹,下面說說如何遍歷這個樹
數(shù)據(jù)表中有字段ID,fatherID即可存儲一個樹,那么如何遍歷這個樹呢?
說明:
一,下面的PlanModel是一個數(shù)據(jù)實體類,其中屬性包括ID,fatherID等
二,方法:PlanBLL.GetChildrenPlanList(......)和 PlanBLL.GetFatherPlan(......)都是自己寫的方法,分別用來訪問子節(jié)點列表和父節(jié)點
三,在外部調用ShowNode()方法,即可成功遍歷。
1 //記錄已經遍歷過的節(jié)點
2 private IList<int> visitedModelIDList = new List<int>();
3
4 //層級系數(shù)
5 private int index = 0;
6
7 /// <summary>
8 /// 遞歸,顯示計劃節(jié)點
9 /// </summary>
10 /// <param name="currentModel">當前節(jié)點實體</param>
11 private void ShowNode(PlanModel currentModel)
12 {
13
14 //如果沒有被遍歷,就顯示該節(jié)點
15 if (visitedModelIDList.Contains(currentModel.ID) == false)
16 {
17 ShowPlanIntoTable(currentModel, index); //顯示到頁面
18 visitedModelIDList.Add(currentModel.ID);
19 }
20
21 //如果有沒有被訪問的子節(jié)點,就轉向該子節(jié)點
22 if (PlanBLL.GetChildrenPlanList(currentModel.ID).Where(m => visitedModelIDList.Contains(m.ID) == false).Count() > 0)
23 {
24 PlanModel model = PlanBLL.GetChildrenPlanList(currentModel.ID).Where(m => visitedModelIDList.Contains(m.ID) == false).First();
25 index++;
26 ShowNode(model);
27 }
28 else //如果沒了未遍歷的子節(jié)點
29 {
30 if(currentModel.FatherID == 0)
31 {
32 return;
33 }
34 else
35 {
36 PlanModel model = PlanBLL.GetFatherPlan(currentModel.FatherID);
37 index--;
38 ShowNode(model);
39 }
40 }
41 }

浙公網安備 33010602011771號