把LIST遞歸成樹形結構


1.創建類

    public class Node
    {
        public bool leaf { get; set; }
        public int FolderID { get; set; }
        public string iconCls { get; set; }
        public bool editable { get; set; }
        public bool expanded { get; set; }
        public int ParentFolderID { get; set; }
        public string text { get; set; }
        public bool InheritPerm { get; set; }
        //public string CreateDate { get; set; }
        //public string CreateBy { get; set; }
        public Node[] children { get; set; }
    }

2.從數據庫獲取數據轉化成LIST

3.遞歸構建樹形結構

        public static string GetTree(List<Node> nodes)
        {
            var list = nodes.FindAll(a => a.ParentFolderID == 1);//最頂級的目錄
            foreach (var node in list)
            {
                if (node.text == "01.通訊錄")
                {
                    node.children = new Node[] { };//必須為空數組,不能為NULL,否則前端樹節點會有錯誤
                }
                GetTree(node, nodes);
            }
            return JsonConvert.SerializeObject(list);
        }


        public static void GetTree(Node paretnNode, List<Node> nodes)
        {
            List<Node> nodelist = new List<Node>();
            foreach (var node in nodes)
            {
                if (node.ParentFolderID == paretnNode.FolderID)
                {
                    GetTree(node, nodes);
                    if (node.children == null)
                    {
                        node.children = new Node[] { };//必須為空數組,不能為NULL,否則前端樹節點會有錯誤
                    }
                    nodelist.Add(node);
                    paretnNode.children = nodelist.ToArray();
                }
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM