2

我有一个时间表列表,这些时间表都在不同的日子开始和结束。当我搜索一周内的所有时间表时,我想列出该周范围内的所有时间段,即使是那些可能开始或结束但一周内有一天或多天的时间段,请参见图像示例:

在此处输入图像描述

为了解决这个问题,我编写了以下代码:

var weekStart = DateTime.Now().Date;
var weekEnd = weekStart.AddDays(6);

var thisWeek = schedules.Where(x =>
        (x.ScheduleStartDate >= weekStart && x.ScheduleStartDate <= weekEnd && x.ScheduleEndDate <= weekEnd && x.ScheduleEndDate >= weekStart) || 
        (x.ScheduleStartDate <= weekStart && x.ScheduleEndDate <= weekEnd && x.ScheduleEndDate >= weekStart) ||
        (x.ScheduleStartDate >= weekStart && x.ScheduleStartDate <= weekEnd && x.ScheduleEndDate >= weekEnd) || 
        (x.ScheduleStartDate <= weekStart && x.ScheduleEndDate >= weekEnd)
    );

这段代码运行良好,所以我现在的问题是是否有办法优化它或者只是让代码看起来更好?

4

2 回答 2

0
var thisWeek = schedules.Where(x =>
        (x.ScheduleStartDate >= weekStart && x.ScheduleStartDate <= weekEnd && x.ScheduleEndDate <= weekEnd && x.ScheduleEndDate >= weekStart) || 
        (x.ScheduleStartDate <= weekStart && x.ScheduleEndDate <= weekEnd && x.ScheduleEndDate >= weekStart) ||
        (x.ScheduleStartDate >= weekStart && x.ScheduleStartDate <= weekEnd && x.ScheduleEndDate >= weekEnd) || 
        (x.ScheduleStartDate <= weekStart && x.ScheduleEndDate >= weekEnd)
    );

如果开始日期小于周末且大于周末,则周开始结束无关紧要。例如,您的约会在一周内开始或结束。
这与结束日期相同

var thisWeek = schedules.Where(x =>
        (x.ScheduleStartDate >= weekStart && x.ScheduleStartDate <= weekEnd) || 
        (x.ScheduleEndDate <= weekEnd && x.ScheduleEndDate >= weekStart)
    );

假设结束日期在开始日期之后并且一周开始于它结束之前,您现在可以进一步减少它

var thisWeek = schedules.Where(x =>
        (x.ScheduleStartDate <= weekEnd && x.ScheduleEndDate >= weekStart)
    );

现在读取约会在一周结束之前开始并在一周开始之后结束。

由于您希望至少有 1 天的重叠

var thisWeek = schedules.Where(x =>
        x.ScheduleStartDate <= weekEnd.AddDays(-1) && x.ScheduleEndDate >= weekStart.AddDays(1)
    );
于 2013-04-26T12:35:02.333 回答
-1

您可以使用具有好名称的函数(甚至 4 个函数)而不是长布尔表达式。该函数当然不会做任何新的事情,但在以后的日子里你会有更好的代码可读性

于 2013-04-26T12:12:11.530 回答