Hierarchy from Flat Data

試著忘記壹切 提交于 2019-11-30 16:27:56

问题


I have an employee class that has an employeeId (int), parent(int) and children property List<Employee>. I get the employee list from the database in the correct order and now need to build the hierarchy, but I am failing miserably...I know this is programming 101, but I am having a hard time with it.

public class Employee
{
  public int EmployeeId { get; set;}
  public int ParentId;{ get; set;}
  public List<Employee> Children; { get; set;}

}

Data Example

EmployeeId, ManagerId
1, 0 //no one
2, 1
3, 1
4, 2
5, 2
6, 3
7, 3

回答1:


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);
}



回答2:


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();
}



回答3:


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



来源:https://stackoverflow.com/questions/4855383/hierarchy-from-flat-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!