Linq查询推荐经理

时间:2014-01-31 08:38:11

标签: c# linq

我在我的LINQ MVC应用程序中有一个要求,即我需要在下拉列表中填写employeeId列表,将mgr分配给员工,他们不是他或他的下属下属的下属。为了使我的观点更清楚,下面是情景 -

Id  MgrId
1 
2    1   
3    
4    2  
5
6    3

我试试

empBO.GetAllEmpList().Where(s => s.Id != model.ID && s.MgrId != model.ID); 

这只适用于一个级别,从上面我选择empid 1进行编辑以指定mgr时,下拉列表应该只包含3,5和6的empid。我在LINQ中没有太多专业知识并且hopt这个可以使用LINQ完成任何建议/帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用递归方法查找给定员工的所有下属(注意,如果层次结构深度很大,您可以使用query/stack implementation而不是递归):

public static IEnumerable<Employee> GetSubordinates(
    IEnumerable<Employee> employees, int employeeId)
{
    foreach (var employee in employees)
    {
        if (employee.MgrId != employeeId)
            continue;

        yield return employee;

        foreach (var subordinate in GetSubordinates(employees, employee.Id))
            yield return subordinate;
    }
}

让员工变得简单:

var employees = GetAllEmpList();
var available = employees.Except(GetSubordinates(employees, selectedId));

此方法将返回具有ID {2,4}的员工。然后调用Enumerable.Except将为您提供所有员工以及直接或间接从属于所选员工的员工。