編寫一個通用遞歸獲取樹形結構對象集合的方法


        /// <summary>
        /// 通用遞歸獲取樹狀子節點信息
        /// </summary>
        /// <param name="item"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private List<T> getTreeListByPid<T, F>(List<F> item, long pid, F d) where T : BaseTreeDto<T>, new() where F : BaseTreeDic, new()
        {
            List<T> ItemsDto = new List<T>();
            //限制條件跳出
            if (item.Where(s => s.Pid == pid).Count() > 0)
            {
                item.Where(s => s.Pid == pid).ToList().ForEach(f =>
                {
                    ItemsDto.Add(new T { Id = f.Id, Name = f.Name, Item = getTreeListByPid<T, F>(item, f.Id, f) });
                });
            }
            return ItemsDto;
        }

 

    public class BaseTreeDto<T>
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public List<T> Item { get; set; }
    }

    public class BaseTreeDic
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public long Pid { get; set; }
    }

 調用方式 將頭節點篩選出來然后傳參進入方法即可(以下是偽代碼)

           
List<T> list = new List<T>(); List<F> item = GetListF(); List<F> tempAllitem = item.Where(i => i.Pid == 0).ToList(); tempAllitem.ForEach(i => { list.Add(new T{ Id = i.Id, Name = i.Name, Item = getTreeListByPid<T, F>(item, i.Id, i) }); });

 


免責聲明!

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



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