Linq to Entities 条件 WHERE

Linq to Entities conditional WHERE

我目前运行以下查询:

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) 行以 if lUserId != 0 为条件(如果不为 0 则使用它,如果为 0 则忽略它)。

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

IQueryble<'a>

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

完成此任务的最佳方法是什么?

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

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

我的理解是:

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

我想你正在寻找这个:

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