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


免責聲明!

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



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