緊接上一篇,將List<Menu>的扁平結構數據, 轉換成樹形結構的數據 返回給前端 , 廢話不多說,開擼!
---------------------
步驟:
1. 建 Menu實體結構
public class Menu { /// <summary> /// ID /// </summary> public int ID { get; set; } /// <summary> /// 菜單名 /// </summary> public string MenuName { get; set; } /// <summary> /// 父菜單 /// </summary> public int ParentID { get; set; } }
2. 建Tree 的數據結構(用來做樹形結構的數據返回)
public class Tree { /// <summary> /// ID /// </summary> public int ID { get; set; } /// <summary> /// 菜單名 /// </summary> public string MenuName { get; set; } /// <summary> /// 父菜單 /// </summary> public int ParentID { get; set; } /// <summary> /// 子節點集合 /// </summary> public List<Tree> Children { get; set; } }
3. 寫方法,遞歸遍歷,將Menu實體值賦值給Tree
//根據父節點獲取子節點 public static List<Tree> GetChildTree(List<Menu> list, int Id) { List<Tree> tree = new List<Tree>(); List<Menu> ChildList = GetChildList(list, Id); foreach (var item in ChildList) { Tree treeB = new Tree(); treeB.ID = item.ID; treeB.MenuName = item.MenuName; treeB.Children = GetChildTree(list,item.ID); tree.Add(treeB); } return tree; } public static List<Menu> GetChildList(List<Menu> list,int Id) { var childList = list.Where(x => x.ParentID == Id).ToList(); return childList; }
4. 准備數據,方法調用
// 准備要處理的數據 List<Menu> listB = new List<Menu>(); listB.Add(new Menu { ID = 1, MenuName = "菜單1", ParentID = 0 }); listB.Add(new Menu { ID = 2, MenuName = "菜單1.1", ParentID = 1 }); listB.Add(new Menu { ID = 3, MenuName = "菜單1.1.1", ParentID = 2 }); listB.Add(new Menu { ID = 4, MenuName = "菜單1.1.2", ParentID = 2 }); listB.Add(new Menu { ID = 5, MenuName = "菜單1.2", ParentID = 1 }); listB.Add(new Menu { ID = 6, MenuName = "菜單1.2.2", ParentID = 5 }); listB.Add(new Menu { ID = 7, MenuName = "菜單2", ParentID = 0 }); var result = GetChildTree(listB, 0); string jsonB = new JavaScriptSerializer().Serialize(result);
5. 轉換后的樹形結構數據結果圖示
-----------------------開發過程中遇到的問題---------------------------------
從別人的博客看到這種方式,很高興,以為改改,很快就可以實現工作中的功能,結果發現還欠缺點東西,就是要傳入的父節點Id值給定的是0 ,寫死的。
而我要傳入的這個Id值要是動態的,要根據傳入的List集合,找出這個集合數據里面的根節點的Id值。 在這上面的代碼中並沒有給出, 於是我開始折騰,最終從別人的js 代碼中找到了別人的解決思路。
我的解決方法如下,希望也能夠幫助一些人:
// 准備要處理的數據 List<Menu> listB = new List<Menu>(); listB.Add(new Menu { ID = 1, MenuName = "菜單1", ParentID = 0 }); listB.Add(new Menu { ID = 2, MenuName = "菜單1.1", ParentID = 1 }); listB.Add(new Menu { ID = 3, MenuName = "菜單1.1.1", ParentID = 2 }); listB.Add(new Menu { ID = 4, MenuName = "菜單1.1.2", ParentID = 2 }); listB.Add(new Menu { ID = 5, MenuName = "菜單1.2", ParentID = 1 }); listB.Add(new Menu { ID = 6, MenuName = "菜單1.2.2", ParentID = 5 }); listB.Add(new Menu { ID = 7, MenuName = "菜單2", ParentID = 0 }); //找出集合里面的根節點的Id HashSet<int> parentIds = new HashSet<int>(); HashSet<int> childIds = new HashSet<int>(); foreach (var item in listB) { childIds.Add(item.ID); parentIds.Add(item.ParentID); } parentIds.ExceptWith(childIds); int rootId = parentIds.First(); var result = GetChildTree(listB, rootId);
最后,發表一下感慨,C# 寫的代碼真的少,7、8行就解決了!