平面数据的层次结构 [英] Hierarchy from Flat Data

查看:82
本文介绍了平面数据的层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个雇员类,其中有一个employeeId(int),parent(int)和子级属性List<Employee>.我以正确的顺序从数据库中获取了雇员列表,并且现在需要构建层次结构.但是我不幸地失败了……我知道这是在编程101,但是我很难它.

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

}

数据示例

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

推荐答案

您可以先创建所有员工对象的列表,然后设置EmployeeIdParentId属性.如果您还将它们放在以EmployeeId键为关键字的字典中,则可以检索每个之后的父级以添加到Children集合中:

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

这篇关于平面数据的层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆