1. 程式人生 > >C# 不用遞迴,獲取無限層級資料

C# 不用遞迴,獲取無限層級資料

物件屬性

 public class ResList
    {
        public int ID { get; set; }
        public List<ResList> Child { get; set; } = null;
        public int Parent { get; set; }
        public int Rank { get; set; }
    }

 

 

  資料就是那種有父級ID的那種

 1             List<ResList> reslist = new
List<ResList>();//新的資料 2 List<ResList> alllist = new List<ResList>();//原始資料 3 //載入原始資料 4 for (int i = 1; i < 10000; i++) 5 { 6 int j = 0; 7 while (Math.Pow(10, j) <= i) 8 { 9 j++;
10 } 11 12 alllist.Add(new ResList() { ID = i, Parent = i / 10, Rank = j }); 13 } 14 //載入原始資料完成 15 16 17 //下面是處理方法 18 Dictionary<int, ResList> dic = new Dictionary<int, ResList>(); 19 20 foreach
(ResList res in alllist) 21 { 22 dic.Add(res.ID, res); 23 24 } 25 foreach (ResList res in dic.Values) 26 { 27 if (dic.ContainsKey(res.Parent)) 28 { 29 if (dic[res.Parent].Child == null) 30 { 31 dic[res.Parent].Child = new List<ResList>(); 32 } 33 dic[res.Parent].Child.Add(res); 34 } 35 } 36 //得到最終的資料List 37 reslist = dic.Values.Where(t => t.Parent == 1).ToList();

 

 

  該方法來源  https://blog.csdn.net/u010162297/article/details/53019101