8,497
社区成员
发帖
与我相关
我的任务
分享
static void Main(string[] args)
{
//调用
Create(ur,0);
//打印
Print(ur);
Console.ReadLine();
}
//测试数据
static List<User> list = new List<User>()
{
new User(){id=1,name="food",parentId=0},
new User(){id=2,name="fruit",parentId=1},
new User(){id=3,name="red",parentId=2},
new User(){id=4,name="cherry",parentId=3},
new User(){id=5,name="yellow",parentId=2},
new User(){id=6,name="banana",parentId=5},
new User(){id=7,name="meat",parentId=1},
new User(){id=8,name="beef",parentId=7},
new User(){id=9,name="pork",parentId=7},
};
//最终结果
static UserR ur = new UserR();
//递归遍历
private static void Create(UserR node, int id)
{
var q = list.Where(x => x.parentId == id).ToList();
if (id == 0) // id = 0 是根节点
{
for (int i = 0; i < q.Count; i++)
{
UserR nd = new UserR();
nd.id = q[i].id;
nd.name = q[i].name;
Create(nd, q[i].id);
ur.u.Add(nd);
}
}
else
{
for (int i = 0; i < q.Count; i++)
{
UserR Tnode = new UserR();
Tnode.id = q[i].id;
Tnode.name = q[i].name;
Create(Tnode, q[i].id);
node.u.Add(Tnode);
}
}
}
//打印查看结果
static void Print(UserR ur)
{
Console.WriteLine(ur.name);
if(ur.u!=null)
foreach (var item in ur.u)
{
Print(item);
}
}
//查询出的实体层
public class User
{
public int id { get; set; }
public string name { get; set; }
public int parentId { get; set; }
}
//遍历后的实体层
public class UserR
{
public int id { get; set; }
public string name { get; set; }
public List<UserR> u = new List<UserR>();
public int parentId { get; set; }
}