LINQ查询时间戳在22:30和1:00之间

时间:2016-10-04 11:08:13

标签: entity-framework linq

我正在尝试使用LINQ获取一个实体列表,其中时间戳在星期六或星期日的22:30 - 24:00或00:00 - 1:00之间,我希望设置两个时间范围一个LINQ查询,但我无法这样做,不得不按如下方式分解:

weekdayNight = intervalInformations.Where(ii => ii.IntervalPeriodTimestamp.TimeOfDay >= new TimeSpan(22, 30, 0)
                                                     && ii.IntervalPeriodTimestamp.TimeOfDay <= new TimeSpan(23, 30, 0)
                                                     && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Saturday
                                                     && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Sunday
                                                     && !dates.Contains(ii.IntervalPeriodTimestamp.ToShortDateString()))
                                                     .OrderBy(ii => ii.IntervalPeriodTimestamp)
                                                     .ToList();


weekdayNight2 = intervalInformations.Where(ii => ii.IntervalPeriodTimestamp.TimeOfDay >= new TimeSpan(0, 0, 0)
                                                     && ii.IntervalPeriodTimestamp.TimeOfDay <= new TimeSpan(0, 30, 0)
                                                     && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Saturday
                                                     && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Sunday
                                                     && !dates.Contains(ii.IntervalPeriodTimestamp.ToShortDateString()))
                                                     .OrderBy(ii => ii.IntervalPeriodTimestamp)
                                                     .ToList();

weekdayNight.Add(weekdayNight2);

如何在不需要加入两个不同查询的情况下编写此查询

1 个答案:

答案 0 :(得分:2)

在定义时间间隔的两个条件之间添加OR应该可以解决问题:

weekdayNight = intervalInformations.Where(ii =>
    ((ii.IntervalPeriodTimestamp.TimeOfDay >= new TimeSpan(22, 30, 0) && ii.IntervalPeriodTimestamp.TimeOfDay <= new TimeSpan(23, 30, 0))
||  (ii.IntervalPeriodTimestamp.TimeOfDay >= new TimeSpan(0, 0, 0) && ii.IntervalPeriodTimestamp.TimeOfDay <= new TimeSpan(0, 30, 0)))
    && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Saturday
    && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Sunday
    && !dates.Contains(ii.IntervalPeriodTimestamp.ToShortDateString())
)
.OrderBy(ii => ii.IntervalPeriodTimestamp)
.ToList();

注意:您的查询似乎排除了23:30到午夜之间的最后半小时。如果这不是故意的,您可以进一步简化查询:

weekdayNight = intervalInformations.Where(ii =>
    (ii.IntervalPeriodTimestamp.TimeOfDay >= new TimeSpan(22, 30, 0)
||  ii.IntervalPeriodTimestamp.TimeOfDay <= new TimeSpan(0, 30, 0))
    && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Saturday
    && ii.IntervalPeriodTimestamp.DayOfWeek != DayOfWeek.Sunday
    && !dates.Contains(ii.IntervalPeriodTimestamp.ToShortDateString())
)
.OrderBy(ii => ii.IntervalPeriodTimestamp)
.ToList();