我有一个场景,我必须在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'但是解决方法是什么?
请帮忙......
答案 0 :(得分:11)
请查看完整的博文:Dynamic query with 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<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);
上述库之间的区别:
答案 1 :(得分:9)
因此,如果flag
为false
,您需要所有Jhoms,如果flag
为真,那么您只需要IT部门的Jhoms
这个条件
!flag || (e.Field<string>("EmployeeDepartment") == "IT"
满足该标准(如果flag为false则始终为true,等等),因此查询将变为:
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")
业务,闻起来像softcoding,可能会对此进行调查。我想
from e in employee
where e.EmployeeName == "Jhom"
&& (!flag || (e.EmployeeDepartment == "IT")
select e.EmployeeID
会更紧凑,更不容易出现输入错误。
编辑:这个答案适用于这种特殊情况。如果您有很多这类查询,请务必将其他答案中提出的模式进行投资。
答案 2 :(得分:2)
你可以链接方法:
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 );
}
答案 3 :(得分:0)
from e in employee
where e.Field<string>("EmployeeName") == "Jhom" &&
(!flag || e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID")
答案 4 :(得分:0)
您可以显式调用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"));
}