在Linq to Sql c#函数中包含或排除where子句

时间:2014-09-17 09:29:57

标签: c# sql linq

问题是我有UI用户可以选择位置和作业,但他们可能会在下拉列表中选择All,如果emplId = 0的值为{1}},则下面的linq应忽略where子句,对于jobId是相同的, 我知道如果使用普通,如果EmplId = 0然后做//东西,如果有一个更干净的方法,我知道如何做到这一点。

public IEnumerable<employees> GetByEmployeIdAndJobId(int EmpId, int JobId)
{
    if (EmplId > 0 && JobId > 0){
    var employees= (from e in Table.Employees
                   where e.employeeId == EmplId && e.JobId == JobId
                   select e).ToList()
    }

    else
    {     var employees= (from e in Table.Employees
                   select e).ToList()
    }
}

2 个答案:

答案 0 :(得分:2)

我猜你的其他部分不包含where子句:

IEnumerable<employees> employees = Table.employees;
if (EmplId > 0 && JobId > 0)
{
  employees = employees.Where(e => (e.employeeId == EmplId && e.JobId == JobId));
}

employees = employees.ToList();

并分别处理EmpID和JobId:

IEnumerable<employees> employees = Table.employees;

if (EmplId > 0)
{
  employees = employees.Where(e => (e.employeeId == EmplId));
}

if (JobId > 0)
{
  employees = employees.Where(e => (e.JobId == JobId));
}

employees = employees.ToList();

答案 1 :(得分:1)

我想你可以使用PredicateBuilder来构建一个谓词来处理用户可以选择的所有场景,如下所示:

public IEnumerable<Employee> GetByEmployeIdAndJobId(int empId, int jobId)
{
    var predicate = PredicateBuilder.True<Employee>();
    if(empId > 0)
        predicate = predicate.And(e => e.EmployeeId == empId);
    if(jobId > 0)
        predicate = predicate.And(e => e.JobId == jobId);
    return Table.Employees.Where(predicate).ToList();
}