加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 动态LINQ中的条件

发布时间:2020-12-15 03:57:53 所属栏目:百科 来源:网络整理
导读:我有一个场景,我必须在LINQ中使用一个动态的条件. 我想要这样的东西: public void test(bool flag){ from e in employee where e.Fieldstring("EmployeeName") == "Jhom" If (flag == true) { e.Fieldstring("EmployeeDepartment") == "IT" } select e.Fiel
我有一个场景,我必须在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”,但是这样做的解决方案是什么?

请帮忙…

解决方法

所以,如果flag是false,那么你需要所有Jhoms,如果flag是true,那么只需要IT部门的Jhoms

这个条件

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

满足该标准(如果标志为false,则始终为真),因此查询将变为:

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

会更紧凑,更不容易输入错误.

编辑:这个答案适用于这个特定场景.如果你有很多这样的查询,一切都意味着投资其他答案中提出的模式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读