间隔起点和终点是正确的事实,不要检查它。我们检查现有区间是否相交有问题的区间:
void Main()
{
var ExistIntervals = new HashSet<Interval>();
//1 Aug 2012 4 Aug 2012
//5 Aug 2012 11 Aug 2012
//12 Aug 2012 15 Aug 2012
ExistIntervals.Add(new Interval { From = new DateTime(2012, 8, 1),
To = new DateTime(2012, 8, 4) });
ExistIntervals.Add(new Interval { From = new DateTime(2012, 8, 5),
To = new DateTime(2012, 8, 11) });
ExistIntervals.Add(new Interval { From = new DateTime(2012, 8, 12),
To = new DateTime(2012, 8, 15) });
var QueryIntervals = new HashSet<Interval>();
//1 Aug 2012 2 Aug 2012 INVALID
//5 Aug 2012 11 Aug 2012 INVALID
//10 Aug 2012 10 Aug 2012 VALID
//15 Aug 2012 15 Aug 2012 INVALID
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 1),
To = new DateTime(2012, 8, 2) });
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 5),
To = new DateTime(2012, 8, 11) });
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 10),
To = new DateTime(2012, 8, 10) });
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 15),
To = new DateTime(2012, 8, 15) });
var result = QueryIntervals.Where( x=> !ExistIntervals.Any(
y=>(y.From <= x.From && x.From <= y.To)
|| (y.From <= x.To && x.To<=y.To)
)
);
result.Dump();
}
public class Interval
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
结果是一个空集。
(结果是一个空集,自 2012 年 8 月 10 日起在此时间间隔内:2012 年 8 月 5 日 ------ 2012 年 8 月 11 日)
您可以使用LinqPad进行测试。
更新:
假设表名“CompaitnDates”、上下文名“CompaitnContext”并确定两个变量的区间:“checkFrom”、“checkTo”。
var checkFrom = new DateTime(2012, 8, 10);
var checkTo = new DateTime(2012, 8, 10);
var db = new CompaitnContext();
那么测试可能如下:
var isValid = !db.CompaitnDates.Any(
y=>(y.From <= checkFrom && checkFrom <= y.To)
|| (y.From <= checkTo && checkTo<=y.To)
);