我正在尝试使用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);
如何在不需要加入两个不同查询的情况下编写此查询
答案 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();