How to build a hierarchy with use Linq to object?

前端 未结 2 2016
既然无缘
既然无缘 2020-12-09 18:52

I have a list of data structures:

        public List Personals()
        {
            return new List
                {
            


        
相关标签:
2条回答
  • Same as above only this code checks for the case that your root node has a ParentID that matches its own ID.

        public void SomeMethod()
        {
            // here you get your `list`
            var tree = GetTree(list, 0);
        }
    
        public List<Tree> GetTree(List<Personal> list, int parent)
        {
            return list.Where(x => x.ParentId == parent).Select(x => new Tree
            {
                Id = x.Id,
                Name = x.Name,
                List = x.ParentId != x.Id ? GetTree(list, x.Id) : new List<Tree>()
            }).ToList();
        }
    
    0 讨论(0)
  • 2020-12-09 19:35

    You should use recursion:

    public void SomeMethod() {
         // here you get your `list`
         var tree = GetTree(list, 0);
    }
    
    public List<Tree> GetTree(List<Personal> list, int parent) {
        return list.Where(x => x.ParentId == parent).Select(x => new Tree {
            Id = x.Id,
            Name = x.Name,
            List = GetTree(list, x.Id)
       }).ToList();
    }
    
    0 讨论(0)
提交回复
热议问题