Linq - 在查询中使用多个变量

时间:2014-04-30 15:06:46

标签: asp.net-mvc linq

我有以下功能: -

    public IEnumerable<Employee> getEmployees(string department, string searchterm)
    {

        IEnumerable<Employee> query;

        if (department == null || department == ""){
            query =  from e in db.Employees  where e.Date_Leave == null orderby e.EmpSurname select e;
        }else{
            query =  from e in db.Employees  where (e.Date_Leave == null) && (e.EmpDept==department) orderby e.EmpSurname select e;
        }

        return query;
    }

目前只是查看'department'变量以确定要运行的查询但我还希望它查看'searchTerm'变量,我将对'EmpSurname'列使用该变量 我的问题是,是否有可能只有一个查询将使用'department'和'searchTerm',如果它们不为null,如果它们为null则忽略它们。也可能是一个是空的而另一个不是。 谢谢

2 个答案:

答案 0 :(得分:0)

您可以通过多个步骤撰写查询,并且在实际请求结果之前不会执行:

public IEnumerable<Employee> getEmployees(string department, string searchterm)
{

    IQueryable<Employee> query = db.Employees.Where(e => e.Data_Leave == null);

    if (department != null && department != "") {
        query = query.Where(e => e.EmpDept == department);
    }

    if(searchterm != null && searchterm != "") {
        query = query.Where(e => e.EmpSurname == searchterm);
    }

    return query.OrderBy(e => e.EmpSurname);
}

答案 1 :(得分:0)

您可以使用:

var query = from e in db.Employees
            where e.Date_Leave == null &&
                  (department == null || e.EmpDept == department) &&
                  (searchTerm == null || /* something using searchTerm */)
            orderby e.EmpSurname
            select e;

或者只是有条件地添加Marcin显示的查询。两种方法都应该没问题。