LINQ中的动态where条件



我有一个场景,我必须在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")
}

我知道我们不能在Linq查询中间使用'If',但解决方案是什么?

请帮…

请查看完整的博客文章:使用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 
}

谓词Builder

谓词生成器的工作原理类似于动态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);

以上库的差异:

  • PredicateBuilder允许构建类型安全的动态查询
  • 动态LINQ库允许使用动态Where和OrderBy子句构建查询,这些子句使用字符串指定。

所以,如果flagfalse,你需要所有的Jhoms,如果flag是真的,你只需要IT部门的Jhoms

这种情况

!flag || (e.Field<string>("EmployeeDepartment") == "IT"

满足该条件(如果标志为假,则始终为真,等等),因此查询将变成:

from e in employee    
where e.Field<string>("EmployeeName") == "Jhom"
  && (!flag || (e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID") 

同样,这个e.Field<string>("EmployeeID")业务,闻起来像软编码,可能会考虑一下。我猜

from e in employee    
where e.EmployeeName == "Jhom"
  && (!flag || (e.EmployeeDepartment == "IT")
select e.EmployeeID

将更紧凑,更不容易出现输入错误。


编辑:这个答案适用于这个特定的场景。如果您有很多这类查询,请务必研究其他答案中提出的模式。

您可以将方法链接:

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<string>("EmployeeName") == "Jhom" &&
(!flag || e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID") 

您可以显式调用LINQ方法并有条件地链接它们。

public IEnumerable<string> FilterEmployees (IEnumerable<Employee> source, bool restrictDepartment)
{
    var query = source.Where (e => e.Field<string>("EmployeeName") == "Jhom");
    if (restrictDepartment) // btw, there's no need for "== true"
        query = query.Where (e => e.Field<string>("EmployeeDepartment") == "IT");
    return query.Select (e => e.Field<string>("EmployeeID"));
}

相关内容

  • 没有找到相关文章

最新更新