1. 程式人生 > >list 遞迴 轉 tree

list 遞迴 轉 tree


        public List<TreeJsonM> GetTreeJsonMList(UserAdmin UserAdmin, ObjType objType)
        {
            Expression<Func<Sys_SupplieCate, bool>> where = a => a.Status != (int)Status.Disable
 && a.CustType == (int)objType && a.CompanyId == UserAdmin.CompanyId && a.UnionId == UserAdmin.UnionID;

            List<Sys_SupplieCate> listDep = GetALL(where).OrderBy(a => a.Id).ToList();


            return ConvertTreeJsonMList(listDep);
        }

        //錯誤的方式
        //List<TreeJsonM> ConvertTreeJsonM(List<Sys_SupplieCate> sys_SupplieCates,int parentId=0)
        //{
        //    List<TreeJsonM> treeJsonMs = new List<TreeJsonM>();
        //    List<Sys_SupplieCate> childs = sys_SupplieCates.Where(a => (a.ParentId==0||a.ParentId==null)
        //    || a.ParentId == parentId).ToList();

        //    if (childs.Count>0)
        //    {
        //        foreach (var item in childs)
        //        {
        //            List<Sys_SupplieCate> aa = sys_SupplieCates;
        //            treeJsonMs.Add(new TreeJsonM() {
        //                id=item.Id,
        //                name = item.Name,
        //                children = ConvertTreeJsonM(aa, item.Id),
        //            });
        //        }
        //    }
        //    return treeJsonMs;
        //}



        List<TreeJsonM> ConvertTreeJsonMList(List<Sys_SupplieCate> sys_SupplieCates, int parentId = 0)
        {
            List<TreeJsonM> treeJsonMs = new List<TreeJsonM>();
            //開始迴圈根節點
            foreach (var item in sys_SupplieCates.Where(a => a.ParentId == 0 || a.ParentId == null).ToList())
            {
                treeJsonMs.Add(ConvertTreeJsonM(sys_SupplieCates, new TreeJsonM() { id=item.Id,
                name=item.Name}));
            }
            return treeJsonMs;
        }

        //賦值節點的子節點集合
        TreeJsonM ConvertTreeJsonM(List<Sys_SupplieCate> sys_SupplieCates, TreeJsonM treeJsonM)
        {

            List<Sys_SupplieCate> childs = sys_SupplieCates.Where(a =>a.ParentId == treeJsonM.id).ToList();
            if (childs.Count > 0)
            {
                List<TreeJsonM> new_childs = new List<TreeJsonM>();
                foreach (var item in childs)
                {
                    TreeJsonM childrens = ConvertTreeJsonM(sys_SupplieCates, new TreeJsonM()
                    {
                        id = item.Id,
                        name = item.Name
                    });
                    new_childs.Add(childrens);
                }
                treeJsonM.children = new_childs;
            }
            return treeJsonM;
        }