Linq multiple where子句与if条件

时间:2016-12-14 06:23:27

标签: c# linq

我正在尝试使用多个where子句编写Linq,并且where子句还包含内联if条件。

List<MeetingVM> students = (
from s in db.Meetings 
where MeetingIsActive == null || s.IsActive == MeetingIsActive 
where MeetingStat == null || MeetingStat == 5 ? (DateTime.UtcNow >= s.MeetingStartTime && DateTime.UtcNow <= s.MeetingStopTime) : s.Status== MeetingStat
where StartDate == null || (s.MeetingStartTime >= StartDate && s.MeetingStartTime <= EndDate) 
where s.Status!=4 
orderby s.MeetingStartTime ascending 
select new MeetingVM
{
    MeetingStartTime = s.MeetingStartTime,
    MeetingStopTime = s.MeetingStopTime,
    Alias = s.Alias,
    MeetingSubject = s.MeetingSubject,
    UserId = s.UserId,
    Status=s.Status

}).ToList();

即使MeetingStat == null,此if条件也会执行(DateTime.UtcNow&gt; = s.MeetingStartTime&amp;&amp; DateTime.UtcNow&lt; = s.MeetingStopTime)。

where MeetingStat == null || MeetingStat==5 ? (DateTime.UtcNow >= s.MeetingStartTime && DateTime.UtcNow <= s.MeetingStopTime) : s.Status== MeetingStat

如果我删除此..

MeetingStat==5 ? (DateTime.UtcNow >= s.MeetingStartTime && DateTime.UtcNow <= s.MeetingStopTime) :

有效。 但我想写这个来检查

if (MeetingStat==5)
  (DateTime.UtcNow >= s.MeetingStartTime && DateTime.UtcNow <= s.MeetingStopTime) 
else 
  s.Status== MeetingStat.

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我认为问题在于DateTime.UtcNow最好将其值存储在变量nad中,然后在LINQ中使用相同的内容,如下所示:

DateTime UtcTime = DateTime.UtcNow;
// and change the condition like this;
.Where MeetingStat != null && MeetingStat==5 ? (UtcTime >= s.MeetingStartTime && UtcTime <= s.MeetingStopTime) : s.Status== MeetingStat

这种情况正在发生,因为Where子句中的谓词没有被转换为SQL,如果你这样使用意味着你的代码将按预期工作,因为UtcTime现在可以转换

答案 1 :(得分:0)

首先,让我们以一种非愚蠢难以阅读的方式获取格式化的代码:

List<MeetingVM> students = (
    from s in db.Meetings 
    where MeetingIsActive == null || s.IsActive == MeetingIsActive 
    where MeetingStat == null || MeetingStat == 5 ? (DateTime.UtcNow >= s.MeetingStartTime && DateTime.UtcNow <= s.MeetingStopTime) : s.Status== MeetingStat
    where StartDate == null || (s.MeetingStartTime >= StartDate && s.MeetingStartTime <= EndDate) 
    where s.Status!=4 
    orderby s.MeetingStartTime ascending 
    select new MeetingVM
    {
        MeetingStartTime = s.MeetingStartTime,
        MeetingStopTime = s.MeetingStopTime,
        Alias = s.Alias,
        MeetingSubject = s.MeetingSubject,
        UserId = s.UserId,
        Status=s.Status

    }).ToList();

那好一点。

现在,我对此并不是百分之百确定,所以知道更好的人可以随意纠正我,但根据C# Operator Precedence,OR(“||”)运算符的优先级高于条件(“?:”)运算符,所以这一行:

where MeetingStat == null || MeetingStat == 5 ? ...

基本上是这样评估的:

where (MeetingStat == null || MeetingStat == 5) ? ...

如果MeetingStat等于true,这将使表达式计算三元运算的第一个分支。从您在问题中的描述来看,这不是您想要的,所以我建议在括号中围绕三元操作以明确您的意图:

where MeetingStat == null || (MeetingStat == 5 ? ... )