我有一个名为DBAppointments的数据库表。该DB由2个字段组成:开始日期和结束日期。我想要做的是计算在某个时间间隔内我有多少次约会。例如,我的表中有2个约会:
App. 1 : 8h30 -> 10h30
App. 2 : 9h -> 10h
更明确一点,我真正做的很简单:我想根据开始日期和持续时间插入新约会。要执行此操作,我必须检查是否可以从特定日期和时间添加约会。再举一个例子:
我想添加一个约会,其持续时间等于2小时。根据我的记录,我将逐步走半小时来确定我能不能。
所以,要做到这一点,那就是我在我的代码中所做的事情:
DBAppointment[] appointmentsOfCurrentDay = (from a in context.DBAppointments where a.StartDate.Value.Date == day.Date select a).ToArray();
foreach (DBAppointment dbapp in appointments)
{
DateTime end = dbapp.PatchExpiration.Value;
for (DateTime startTime = dbapp.StartDate.Value; startTime <= end; startTime = startTime.AddHours(0.5))
{
**int countAppointment = appointmentsOfCurrentDay.Count(a => a.StartDate <= startTime && startTime.AddHours(duration) <= a.EndDate);**
if (countAppointment < maxBeds && (Math.Ceiling(Decimal.ToDouble(dbapp.PatchQuantity.Value)) - Decimal.ToDouble(dbapp.PatchQuantity.Value) >= patchQuantity))
{
IntervalViewModel ivm = new IntervalViewModel();
ivm.StartDate = startTime;
ivm.EndDate = startTime.AddHours(duration);
listValidIntervals.Add(ivm);
}
}
我的问题在于代码行以粗体显示。我们从8点30分开始,到10点30分结束,所以我的计数等于2是正确的。但是,当我们执行第二次迭代(因此startime等于9h)时,计数显示为1,这是不正确的。
我明白为什么(因为我们说a.StartDate比startime更好或更等)但我不知道如何修复它。
答案 0 :(得分:1)
只需查看:int countAppointment = appointmentsOfCurrentDay.Count(a => a.StartDate <= startTime && startTime.AddHours(duration) <= a.EndDate);
应该是:int countAppointment = appointmentsOfCurrentDay.Count(a => a.StartDate <= startTime && a.EndDate >= startTime.AddHours(duration));
以前你有:
第一次迭代:ivm.StartDate = 8h30 ; ivm.StartDate.AddHours(2) = 10h30
test : 8h30 <= 8h30 && 10h30 <= 10h30 (true)
第二次迭代:ivm.StartDate = 9h00 ; ivm.StartDate.AddHours(2) = 11h00
test: 9h00 <= 9h00 && 11h <= 10h00 (false)
答案 1 :(得分:0)
我改变了我的代码,也许这样:
int countAppointment = appointmentsOfCurrentDay.Count(a => (startTime >= a.StartDate && startTime < a.EndDate || startTime.AddHours(duration) > a.StartDate && startTime.AddHours(duration) <= a.EndDate) ||
(a.StartDate >= startTime && a.StartDate < startTime.AddHours(duration) || a.EndDate > startTime && a.EndDate <= startTime.AddHours(duration)));
答案 2 :(得分:0)
我已经写了这个小例子来解释我的评论,希望它有助于解决您的问题。很抱歉懒得重写你的代码。如果您需要进一步的帮助,请告诉我
private List<DateTime> ValidEndTime = new List<DateTime>(); //Contains the list of validEndDate
private void button1_Click(object sender, EventArgs e)
{
List<DateTime> currentAppointment = new List<DateTime>();
currentAppointment.Add(Convert.ToDateTime("22 May 2014 14:22"));
currentAppointment.Add(Convert.ToDateTime("22 May 2014 14:30"));
foreach (DateTime endDate in currentAppointment)
{
if (IsAppointmentTimeValid(endDate) == true)
{
ValidEndTime.Add(endDate);
}
}
}
private bool IsAppointmentTimeValid(DateTime newAppointmentEndTime)
{
//compare max(maxendDateTime) with the newAppointmentDateTime
return ValidEndTime.Max(t => t.Date) < newAppointmentEndTime? true : false;
}