如何在层次结构中上移以找到顶级经理?

时间:2019-10-07 15:10:12

标签: c#

我正在尝试为多层层次结构中的员工寻找顶级经理。

我尝试过的工作给了我直接的经理,但没有给我最高的经理。

public Employee GetManager(Employee employee)
{
    Employee topManager = new Employee();

    Stack<Employee> managers = new Stack<Employee>();

    if (employee.ManagerId == null)
    {
        topManager = employee; //CEO ---
    }
    else
    {

        using (var context = new EmployeeContext())
        {
            var manager = context.Employees.FirstOrDefault(e => e.Id == employee.ManagerId);
            managers.Push(manager);
            GetManager(manager);
        }

        topManager = managers.Peek();
    }
    return topManager;
}

2 个答案:

答案 0 :(得分:1)

为什么不创建一个循环并像这样:

Employee targetManager = employee;
while(targetManager.managerid != null) 
    targetManager = context.Employees.FirstOrDefault(e => e.Id == targetManager.ManagerId);

答案 1 :(得分:1)

这总是返回直接管理器,因为在每个递归调用中,您正在创建一个新堆栈,该堆栈将由函数参数employee的直接管理器填充。

如果您真的想使用递归,则需要将managers设为一个变量,每次进行递归调用时都不会对其进行初始化,因此如下所示:

public Employee GetManager(Employee employee)
{
    Stack<Employee> managers = new Stack<Employee>();

    BuildManagerStack(employee);
    return managers.Peek();

    void BuildManagerStack(Employee e)
    {
        if (employee.ManagerId == null)
        {
            managers.Push(e);
        }
        else
        {
            using (var context = new EmployeeContext())
            {
                var manager = context.Employees.FirstOrDefault(e => e.Id == employee.ManagerId);
                managers.Push(manager);
                BuildManagerStack(manager);
            }
    }
}

我鼓励您尝试不使用递归来解决此问题:您将获得更干净,更易读,更高效的解决方案:)