问题描述
我有一种情况,我必须使用动态条件的地方在LINQ。
I have a scenario where I have to use a dynamic where condition in LINQ.
我想是这样的:
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查询的中间,但如何解决此?
I know we can't use the 'If' in the middle of the Linq query but what is the solution for this?
请帮忙...
推荐答案
所以,如果标志
是假
您需要的所有Jhoms,如果标志
是真实的,你只需要Jhoms IT部门
So, if flag
is false
you need all Jhoms, and if flag
is true you need only the Jhoms in the IT department
这条件
!flag || (e.Field<string>("EmployeeDepartment") == "IT"
满足这一标准(它总是真,如果标志是假的,等..),所以查询将变为:
satisfies that criterion (it's always true if flag is false, etc..), so the query will become:
from e in employee
where e.Field<string>("EmployeeName") == "Jhom"
&& (!flag || (e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID")
此外,该 e.Field<串GT;(雇员)
业务,闻起来像,可能对员工
其中e看一看成说。我猜
also, this e.Field<string>("EmployeeID")
business, smells like softcoding, might take a look into that. I guess
from e in employee
where e.EmployeeName == "Jhom"
&& (!flag || (e.EmployeeDepartment == "IT")
select e.EmployeeID
将更加紧凑,不容易打字错误。
would be more compact and less prone to typing errors.
编辑:这个答案适用于这个特定的场景。如果你有很多这种类型的查询中,通过各种手段在investingate其他的答案提出的模式。
This answer works for this particular scenario. If you have lots of this kinds of queries, by all means investingate the patterns proposed in the other answers.
这篇关于在LINQ动态where条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!