Shi*_*ivi 11 c# linq linq-to-sql dynamicquery
我有一个场景,我必须在LINQ中使用动态where条件.
我想要这样的东西:
public void test(bool flag)
{
from e in employee
where e.Field<string>("EmployeeName") == "Jhom"
If (flag == true)
{
e.Field<string>("EmployeeDepartment") == "IT"
}
select e.Field<string>("EmployeeID")
}
Run Code Online (Sandbox Code Playgroud)
我知道我们不能在Linq查询的中间使用'If'但是这个解决方案是什么?
请帮忙...
Pra*_*ana 11
请查看完整的博客文章:使用Linq进行动态查询
您可以使用两个选项:
string condition = string.Empty;
if (!string.IsNullOrEmpty(txtName.Text))
condition = string.Format("Name.StartsWith(\"{0}\")", txtName.Text);
EmployeeDataContext edb = new EmployeeDataContext();
if(condition != string.empty)
{
var emp = edb.Employees.Where(condition);
///do the task you wnat
}
else
{
//do the task you want
}
Run Code Online (Sandbox Code Playgroud)
谓词构建器的工作方式类似于动态LINQ库,但它是类型安全的:
var predicate = PredicateBuilder.True<Employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
Run Code Online (Sandbox Code Playgroud)
以上库之间的区别:
所以,如果flag是false你需要的所有Jhoms,如果flag是真的,你只需要Jhoms IT部门
这种情况
!flag || (e.Field<string>("EmployeeDepartment") == "IT"
Run Code Online (Sandbox Code Playgroud)
满足该标准(如果flag为false则总是如此......),因此查询将变为:
from e in employee
where e.Field<string>("EmployeeName") == "Jhom"
&& (!flag || (e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID")
Run Code Online (Sandbox Code Playgroud)
此外,这项e.Field<string>("EmployeeID")业务,闻起来像软编码,可能会考虑到这一点.我猜
from e in employee
where e.EmployeeName == "Jhom"
&& (!flag || (e.EmployeeDepartment == "IT")
select e.EmployeeID
Run Code Online (Sandbox Code Playgroud)
会更紧凑,更不容易出现打字错误.
编辑:这个答案适用于这种特殊情况.如果您有很多这类查询,请务必投入其他答案中提出的模式.