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”,但是解决方案是什么?
请帮忙...
I have a scenario where I have to use a dynamic where condition in LINQ.
I want something like this:
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")
}
I know we can't use the 'If' in the middle of the Linq query but what is the solution for this?
Please help...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请查看完整的博客文章:使用 Linq 进行动态查询
您可以使用两个选项:
动态 LINQ 库
谓词构建器
谓词构建器的工作方式与动态 LINQ 库类似,但它是类型安全的:
上述库之间的区别:
Please check out the full blog post: Dynamic query with Linq
There are two options you can use:
Dynamic LINQ library
Predicate Builder
Predicate builder works similar to Dynamic LINQ library but it is type safe:
difference between above library:
因此,如果
flag
为false
,您需要所有 Jhom,如果flag
为 true,您只需要 IT 部门的 Jhom。此条件
满足: criteria(如果 flag 为 false,则始终为 true,等等),因此查询将变为:
此外,此
e.Field("EmployeeID")
业务,闻起来像 softcoding,可能会看看。我想会更紧凑并且不太容易出现打字错误。
编辑:这个答案适用于这个特定的场景。如果您有很多此类查询,请务必研究其他答案中提出的模式。
So, if
flag
isfalse
you need all Jhoms, and ifflag
is true you need only the Jhoms in the IT departmentThis condition
satisfies that criterion (it's always true if flag is false, etc..), so the query will become:
also, this
e.Field<string>("EmployeeID")
business, smells like softcoding, might take a look into that. I guesswould be more compact and less prone to typing errors.
EDIT: 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.
您可以链接方法:
You can chain methods :
您可以显式调用 LINQ 方法并有条件地链接它们。
You can call LINQ methods explicitly and chain them conditionally.