动态LINQ中的条件
我有一个场景,我必须在LINQ中使用动态where条件。
我想要这样的东西:
public void test(bool flag) { from e in employee where e.Field("EmployeeName") == "Jhom" If (flag == true) { e.Field("EmployeeDepartment") == "IT" } select e.Field("EmployeeID") }
我知道我们不能在Linq查询的中间使用’If’但是这个解决方案是什么?
请帮忙…
因此,如果flag
为false
,则需要所有Jhoms,如果flag
为true,则只需要IT部门中的Jhoms
这种情况
!flag || (e.Field("EmployeeDepartment") == "IT"
满足该标准(如果flag为false则始终为true,等等),因此查询将变为:
from e in employee where e.Field("EmployeeName") == "Jhom" && (!flag || (e.Field ("EmployeeDepartment") == "IT") select e.Field ("EmployeeID")
此外,这个e.Field
业务,闻起来像软编码 ,可能会考虑到这一点。 我猜
from e in employee where e.EmployeeName == "Jhom" && (!flag || (e.EmployeeDepartment == "IT") select e.EmployeeID
会更紧凑,更不容易出现打字错误。
编辑:这个答案适用于这种特殊情况。 如果您有很多这类查询,请务必投入其他答案中提出的模式。
请查看完整的博文: 使用Linq进行动态查询
您可以使用两个选项:
动态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 }
谓词生成器
谓词构建器的工作方式类似于动态LINQ库,但它是类型安全的:
var predicate = PredicateBuilder.True(); if(!string.IsNullOrEmpty(txtAddress.Text)) predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text)); EmployeeDataContext edb= new EmployeeDataContext(); var emp = edb.Employees.Where(predicate);
以上库之间的区别:
- PredicateBuilder允许构建类型安全的动态查询 。
- 动态LINQ库允许使用使用字符串指定的动态Where和OrderBy子句构建查询。
你可以链方法:
public void test(bool flag) { var res = employee.Where( x => x.EmployeeName = "Jhom" ); if (flag) { res = res.Where( x => x.EmployeeDepartment == "IT") } var id = res.Select(x => x.EmployeeID ); }
from e in employee where e.Field("EmployeeName") == "Jhom" && (!flag || e.Field ("EmployeeDepartment") == "IT") select e.Field ("EmployeeID")
您可以显式调用LINQ方法并有条件地链接它们。
public IEnumerable FilterEmployees (IEnumerable source, bool restrictDepartment) { var query = source.Where (e => e.Field("EmployeeName") == "Jhom"); if (restrictDepartment) // btw, there's no need for "== true" query = query.Where (e => e.Field ("EmployeeDepartment") == "IT"); return query.Select (e => e.Field ("EmployeeID")); }