Dynamic where condition in LINQ(LINQ 中的动态 where 条件)
问题描述
我有一个场景,我必须在 LINQ 中使用动态 where 条件.
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 查询中间使用If",但是对此有什么解决方案?
I know we can't use the 'If' in the middle of the Linq query but what is the solution for this?
请帮忙...
推荐答案
所以,如果 flag
是 false
你需要所有 Jhoms,如果 flag
是的,您只需要 IT 部门的 Jhoms
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
业务,闻起来像 软编码,可能会考虑一下.我猜
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.
此答案适用于此特定场景.如果您有很多此类查询,请务必投资其他答案中提出的模式.
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 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ 中的动态 where 条件


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01