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的那种

             List<ResList> reslist = new List<ResList>();//新的数据
List<ResList> alllist = new List<ResList>();//原始数据
//加载原始数据
for (int i = ; i < ; i++)
{
int j = ;
while (Math.Pow(, j) <= i)
{
j++;
} alllist.Add(new ResList() { ID = i, Parent = i / , Rank = j });
}
//加载原始数据完成 //下面是处理方法
Dictionary<int, ResList> dic = new Dictionary<int, ResList>(); foreach (ResList res in alllist)
{
dic.Add(res.ID, res); }
foreach (ResList res in dic.Values)
{
if (dic.ContainsKey(res.Parent))
{
if (dic[res.Parent].Child == null)
{
dic[res.Parent].Child = new List<ResList>();
}
dic[res.Parent].Child.Add(res);
}
}
//得到最终的数据List
reslist = dic.Values.Where(t => t.Parent == ).ToList();
 

  该方法来源  https://blog.csdn.net/u010162297/article/details/53019101