我正在尝试确定时间范围是否在 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 页面的布局。
最佳答案
这实际上比看起来更棘手,因为您需要处理跨越午夜的时间段。
使用一些扩展方法,你可以让它变得直接。
首先,判断一个时间是否在另外两个时间之间:
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/