我有一个具有多个搜索条件的表单,用户可以使用它来搜索员工数据,例如FirstName,LastName,HireDate,Department等.
我正在使用LINQ,我想知道在给定任何搜索条件的情况下,我可以使用什么方法来查询Employes集合,即用户不必输入所有,但他们必须至少输入一个搜索参数.
到目前为止,在测试我的LINQ语句时,有两个搜索参数,似乎我必须查看是否输入了搜索参数.如果是这种情况,那么对于许多搜索参数来说这可能变得非常笨重.
// only FirstName is entered
if (!string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName))
{
var employees = DB.Employees
.Where(emp => emp.FirstName.Contains(fName));
}
// only LastName is entered
else if (string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName))
{
var employees = DB.Employees
.Where(emp => emp.LastName.Contains(lName));
}
// both parameters are entered
else if (!string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName))
{
var employees = DB.Employees
.Where(emp => emp.FirstName.Contains(fName))
.Where(emp => emp.LastName.Contains(lName));
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,我最初认为我可以使用相关的搜索参数将Where()语句附加到我的LINQ语句中,但我注意到并非所有记录都应该返回,因此if-then语句的上述逻辑也是如此.
这样的事情怎么样:
IQueryable<Employee> employees = DB.Employees;
if (!string.IsNullOrEmpty(FirstName))
{
employees = employees
.Where(emp => emp.FirstName.Contains(fName));
}
if (!string.IsNullOrEmpty(LastName))
{
employees = employees
.Where(emp => emp.Last.Contains(lName));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1775 次 |
| 最近记录: |