线形集合转换树形结构

public class A
{
    public int Id { get; set; }
    public int Pid { get; set; }
    public string Name { get; set; }
}

public class B
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<B> Children { get; set; }
}

public List<B> ConvertToTree(List<A> linearList, int parentId = 0)
{
    List<B> treeList = new List<B>();

    foreach (var item in linearList.Where(x => x.Pid == parentId))
    {
        B node = new B
        {
            Id = item.Id,
            Name = item.Name,
            Children = ConvertToTree(linearList, item.Id)
        };

        treeList.Add(node);
    }

    return treeList;
}

List<A> linearList = new List<A>
{
    new A { Id = 1, Pid = 0, Name = "Node 1" },
    new A { Id = 2, Pid = 1, Name = "Node 1.1" },
    new A { Id = 3, Pid = 1, Name = "Node 1.2" },
    new A { Id = 4, Pid = 2, Name = "Node 1.1.1" },
    new A { Id = 5, Pid = 0, Name = "Node 2" },
    new A { Id = 6, Pid = 5, Name = "Node 2.1" },
    new A { Id = 7, Pid = 5, Name = "Node 2.2" }
};

List<B> treeList = ConvertToTree(linearList);

 

posted @ 2023-09-05 10:53  森雾  阅读(6)  评论(0编辑  收藏  举报