Hierarchy from Flat Data

前端 未结 3 718
闹比i
闹比i 2021-01-03 16:38

I have an employee class that has an employeeId (int), parent(int) and children property List. I get the employee list from the database in the

相关标签:
3条回答
  • 2021-01-03 17:11

    You can start by creating a list of all the employee objects and setting the EmployeeId and ParentId properties. If you also put them in a dictionary, keyed by EmployeeId, you can retrieve the parent of each afterward to add to the Children collection:

    List<Employee> employees = new List<Employee>();
    Dictionary<int,Employee> dict = new Dictionary<int,Employee>();
    
    foreach(result from database query)
    {
       Employee employee = new Employee();
       employee.EmployeeId = result["EmployeeId"];
       employee.ParentId = result["ParentId"];
       employees.Add(employee);
       dict.Add(employee.EmployeeId, employee);
    }
    
    foreach(Employee e in employees)
    { 
      dict[e.ParentId].Children.Add(e);
    }
    
    0 讨论(0)
  • 2021-01-03 17:14

    i got inspiration from this article a while ago (i had to change it slightly to suit my purposes). It basically builds a hierarchical structure to the n'th degree.

    Might be useful, even if only to discount its approach in your own case :-)

    http://www.scip.be/index.php?Page=ArticlesNET23&Lang=EN

    0 讨论(0)
  • 2021-01-03 17:32
    List<Employee> allEmployees = new List<Employee>();
    allEmployees.AddRange(LoadAllEmployees()); // pull from DB in flat format    
    foreach (var employee in allEmployees)
    {
      employee.Children = allEmployees.Where(e => e.ParentId == employee.EmployeeId).ToList();
    }
    
    0 讨论(0)
提交回复
热议问题