【问题标题】:Linq to Entities conditional WHERELinq to Entity 有条件的 WHERE
【发布时间】:2017-06-20 12:30:38
【问题描述】:

我目前正在运行以下查询:

var results = from c in _context.Cs
              join a in _context.Ca on c.Id equals a.CId
              where c.Status == "A"
              where c.CtId == ctId
              where c.FY == fYear
              where (a.PMId == lUserId || a.TLId == lInUserId)
              select new { c.Id, c.T, c.C, c.S } into x
              group x by new {x.Id, x.T, x.C, x.S} into g
              orderby g.Key.T, g.Key.C, g.Key.S
              select new { Id = g.Key.Id, T = g.Key.T, C = g.Key.C, S = g.Key.S}

现在我需要使where (a.PMId == lUserId || a.TLId == lInUserId) 行以 lUserId != 0 为条件(如果不是 0 则使用它,如果为 0 则忽略它)。

通常,我会声明变量results,然后在 if 语句中设置它,但我不知道如何定义这个数据结构。它显示为被定义为:

IQueryble<'a>

'a is new { int Id, string T, string C, string S}

最好的方法是什么?

【问题讨论】:

    标签: c# .net linq-to-entities iqueryable anonymous-types


    【解决方案1】:

    您可以在查询中使用|| 运算符,因此如果第一个条件为真,则不计算第二个条件,如果第一个条件不等于 0,则将计算第二个条件:

    where lUserId ==0 || (a.PMId == lUserId || a.TLId == lInUserId)
    

    【讨论】:

    • 这很简单。有时我只见树木不见森林。嘘!谢谢!!!
    【解决方案2】:

    我的理解是:

    • 当且仅当UserId != 0 使用条件a.PMId == lUserId || a.TLId == lInUserId
    • 如果lUserId ==0 则忽略该条件 如果我正确理解了要求,那么&amp;&amp; 将是您必须在此处使用的运算符。因为如果第一个条件为假(即UserId == 0),它将跳过检查第二个条件

    我想你正在寻找这个:

    where (UserId != 0 && a.PMId == lUserId || a.TLId == lInUserId)
    

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      相关资源
      最近更新 更多