[英]Linq to Entities conditional WHERE
I'm currently running the following query: 我当前正在运行以下查询:
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}
Now I need to make the where (a.PMId == lUserId || a.TLId == lInUserId)
line conditional on if lUserId != 0 (use it if not 0, ignore it if 0). 现在,我需要将
where (a.PMId == lUserId || a.TLId == lInUserId)
行作为条件,如果lUserId!= 0(如果不为0,则使用它;如果为0,则忽略它)。
Normally, I would declare the variable results
then set it in an if statement, but I have no idea how to define this data structure. 通常,我将声明变量
results
然后在if语句中对其进行设置,但是我不知道如何定义此数据结构。 It shows as being defined as: 它显示为:
IQueryble<'a>
'a is new { int Id, string T, string C, string S}
Whats the best way to accomplish this? 最好的方法是什么?
You can use ||
您可以使用
||
operator in the query so if first condition is true, the second will not be evaluated and if first is false that is not equal to 0 second will be evaluated: 查询中的运算符,因此,如果第一个条件为true,则将不评估第二个条件;如果first为false,则不等于0秒将被评估:
where lUserId ==0 || (a.PMId == lUserId || a.TLId == lInUserId)
What I understand is: 我的理解是:
a.PMId == lUserId || a.TLId == lInUserId
a.PMId == lUserId || a.TLId == lInUserId
a.PMId == lUserId || a.TLId == lInUserId
if and only if UserId != 0
a.PMId == lUserId || a.TLId == lInUserId
当且仅当UserId != 0
lUserId ==0
If I understand the requirement correctly, then &&
will be the operator that you have to use here. lUserId ==0
则忽略该条件。如果我正确理解了要求,那么&&
将是您在此处必须使用的运算符。 since it will skip checking the second condition if the first condition is false(that is UserId == 0
). UserId == 0
),它将跳过检查第二个条件 。 I think you are looking for this: 我认为您正在寻找:
where (UserId != 0 && a.PMId == lUserId || a.TLId == lInUserId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.