Skip to main content
 首页 » 编程设计

c#之平面数据的层次结构

2024年02月23日17zhoujg

我有一个员工类,它有一个 employeeId (int)、parent(int) 和 children 属性 List<Employee> .我以正确的顺序从数据库中获取员工列表,现在需要构建层次结构,但我失败得很惨......我知道这是编程 101,但我很难

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

数据示例

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

请您参考如下方法:

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