我的网格视图接受用于为特定团队计划行程的数据。我需要他们的行程不能与任何其他日期发生冲突。
考虑以下场景。
------------------------------------------
| TripName | FromDate | ToDate |
------------------------------------------
| Delhi | 01/11/2018 | 05/11/2018 |
| Chennai | 07/11/2018 | 12/11/2018 |
| Bengaluru | 06/11/2018 | 11/11/2018 |
------------------------------------------最后一个条目无效,因为它与第二个行程冲突。我需要避免这种情况的发生。
发布于 2018-11-20 15:27:25
因此,如果我理解得很好,您应该检查一下datetime之间是否有任何交集。
更新:
定义一个有间隔的类:
class DateTimeInterval
{
public DateTime Start { get; }
public DateTime End { get; }
public TimeSpan Length { get { return End - Start; } }
public DateTimeInterval(DateTime startDate, DateTime endDate)
{
if (endDate < startDate)
throw new ArgumentException();
Start = startDate;
End = endDate;
}
public bool Intersect(DateTimeInterval other)
{
if((other.Start <= Start && other.End >= Start) || //left intersect
(other.End >= End && other.Start <= End) || //right intersect
(other.Start >= Start && other.End <= End)) //middle intersect
{
return true;
}
return false;
}
static public bool Intersect(DateTimeInterval dti1, DateTimeInterval dti2)
{
if ((dti1.Start <= dti2.Start && dti1.End >= dti2.Start) || //left intersect
(dti1.End >= dti2.End && dti1.Start <= dti2.End) || //right intersect
(dti1.Start >= dti2.Start && dti1.End <= dti2.End)) //middle intersect
{
return true;
}
return false;
}
}并在这里使用该类的测试示例:
List<DateTimeInterval> dtiList = new List<DateTimeInterval>();
DateTimeInterval dtInterval = new DateTimeInterval(new DateTime(2018, 09, 10), new DateTime(2018, 09, 20));
dtiList.Add(new DateTimeInterval(new DateTime(2018, 06, 12), new DateTime(2018, 7, 1)));
dtiList.Add(new DateTimeInterval(new DateTime(2018, 09, 05), new DateTime(2018, 09, 15)));
dtiList.Add(new DateTimeInterval(new DateTime(2018, 09, 12), new DateTime(2018, 09, 20)));
dtiList.Add(new DateTimeInterval(new DateTime(2018, 09, 11), new DateTime(2018, 09, 15)));
dtiList.Add(new DateTimeInterval(new DateTime(2018, 09, 5), new DateTime(2018, 09, 9)));
foreach(var dti in dtiList)
{
Console.WriteLine(DateTimeInterval.Intersect(dtInterval, dti));
}如果您有DateInterval0、DateInterval1、DateInterval2、DateInterval3、DateIntervalN,则必须检查
在你的程序中,像下面这样检查intersect:
for(var i = 0; i < dates.Length-2; ++i)
for(var j = i+1; i < dates.Length-1; ++j)
DateTimeInterval.Intersect(datesInterval[i], datesInterval[j]);https://stackoverflow.com/questions/53387735
复制相似问题