c# - 重叠 C# 3 次或更多次

标签 c# datetime

我正在尝试确定时间范围是否在 CRUD 页面上重叠但卡住了。

我可以使用下面的代码让它在两个时间范围内工作,但我也需要它在 3 个时间范围内工作。

public static bool IsOverLapping(ConfigureViewModel viewModel)
{
    bool status = false;
    var times = viewModel.Periods.OrderBy(x => x.StartTime.TimeOfDay).ToList();
    for (var i = 0; i <= times.Count - 2; i++)
    {
        if (times[i].StartTime.TimeOfDay <= times[i + 1].EndTime.TimeOfDay)
        {
            if (times[i + 1].StartTime.TimeOfDay >= times[i].EndTime.TimeOfDay)
                status = false;
            else
                return true;
        }
        else
            return true;
    }
    return status;
}

数据以 DateTime 值的形式出现,这就是为什么我只查看“TimeOfDay”值的原因。该图显示了 CRUD 页面的布局。

enter image description here

最佳答案

这实际上比看起来更棘手,因为您需要处理跨越午夜的时间段。

使用一些扩展方法,你可以让它变得直接。

首先,判断一个时间是否在另外两个时间之间:

public static bool Between(this TimeSpan aTime, TimeSpan startTime, TimeSpan endTime) => (startTime <= endTime) ? (startTime < aTime && aTime < endTime)
                                                                                                                : (startTime < aTime || aTime < endTime);

然后使用范围的 Period 类创建一个特殊版本:

public static bool Between(this TimeSpan aTime, Period aPeriod) => aTime.Between(aPeriod.StartTime.TimeOfDay, aPeriod.EndTime.TimeOfDay);

最后创建一个测试是否一个范围与第二个范围重叠(注意这是不对称的):

public static bool Overlaps(this Period aPeriod, Period bPeriod) => aPeriod.StartTime.TimeOfDay.Between(bPeriod) || aPeriod.EndTime.TimeOfDay.Between(bPeriod);

现在遍历所有范围并检查是否有任何范围与另一个范围重叠:

public static bool IsOverLapping(this List<Period> periods) {
    var periodCount = periods.Count;
    for (int j1 = 0; j1 < periodCount; ++j1)
        for (int j2 = 0; j2 < periodCount; ++j2)
            if (j1 != j2 && periods[j1].Overlaps(periods[j2]))
                return true;
    return false;
}

最后,您可以在 ConfigureViewModel 方法中使用该方法:

public static bool IsOverLapping(ConfigureViewModel viewModel)
{
    bool status = false;
    var times = viewModel.Periods.OrderBy(x => x.StartTime.TimeOfDay).ToList();
    return times.IsOverLapping();
}

关于c# - 重叠 C# 3 次或更多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49866980/

相关文章:

python - 如何将日期时间增加一天?

python - 元组到日期时间

ios - 如何将日期字符串从 Rails 转换为 Swift

python - 在 Python 中从日期中减去 n 天

c# - 找不到类型或命名空间名称 'OwinStartupAttribute'

c# - 如何在 .NET 4.0 中使用 Microsoft.Bcl.Async 支持 TransactionScope 中的异步方法?

c# - WinForms:控件的最大大小为 65535 - 解决方法?

sql - Postgresql CASE 语法的问题

c# - 编写一个可以等待的异步进程

c# - 组合框 SelectedItem 无法正常工作