转换SQL分层数据

时间:2013-03-14 22:16:27

标签: c# recursion

我有一个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; }
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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

一旦它们全部被读取,迭代并用Employee s引用替换ID。

foreach (var employee in employees)
{
    foreach (var id in employee.ChildrenIDs)
    {
        employee.Children.Add(employees[id]);
    }
}