Building hierarchy objects from flat list of parent/child

前端 未结 6 526
花落未央
花落未央 2021-01-30 18:07

I have a list of items in a hierarchy, and I\'m attempting to parse this list out into an actual hierarchy of objects. I\'m using modified pre-order tree traversal to store/iter

6条回答
  •  旧时难觅i
    2021-01-30 18:58

    Correcting the example given by gregmac

    IList FlatToHierarchy(IQueryable list, int? parentId)
        {
            var q = (from i in list
                    where i.parent_id == parentId
                    select new
                    {
                        id = i.id,
                        parent_id = i.parent_id,
                        kks = i.kks,
                        nome = i.nome
                    }).ToList();
            return q.Select(x => new TreeObject
                {
                    children = FlatToHierarchy(list, x.id)
                }).ToList();
        }
    

提交回复
热议问题