1

我有一个sql数据

ID Name ParentID
1 BillGates 1
2 Paul Allen 1
3 Progam manager 2
4 Some Programmer 3

……

我如何将其递归到List<Employee>员工所在的位置

public  class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Employee> Children { get; set; }
}
4

2 回答 2

1

要递归地获取员工下的所有员工,您可以使用以下函数:

    public IEnumerable<T> GetDescendents<T>(T parent, Func<T, IEnumerable<T>> childSelector)
    {
        yield return parent;

        foreach (var child in childSelector(parent))
        {
            foreach (var grandChild in GetDescendents(child, childSelector))
            {
                yield return grandChild;
            }
        }
    }

示例用法:

var allChildEmployees = GetDescendents(employee, e => e.Children);
于 2013-03-14T22:23:28.037 回答
0

您需要保留以下字典Employee

Dictionary<int, Employee> employees;

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<int> ChildrenIDs { get; set; }
    public List<Employee> Children { get; set; }
}

首先,直接阅读您的员工,阅读他们的父母ID

一旦它们都被读取,迭代并用Employees 引用替换 ID。

foreach (var employee in employees)
{
    foreach (var id in employee.ChildrenIDs)
    {
        employee.Children.Add(employees[id]);
    }
}
于 2013-03-14T22:18:20.543 回答