c#查询重叠日期

时间:2018-11-27 16:38:46

标签: c# winforms linq

我要检查此特定房间是否已经预订:

bool overlaps = false;

这种方法只能找到值为roomId first 5,因为它是FirstOrDefault();

var room = (from u in db.Reservation
             where u.RoomId == roomId
             select u  
           ).FirstOrDefault();

if((StartDateWantToBook <= room.EndDate) && (room.StartDate <= EndDateWantToBook))
{
     overlaps = true;
     MessageBox.Show("This room is already reserved");
}
else
{
   // Process to reserv this room
overlaps = false;
}

但是,如果我的roomId在具有不同开始和结束日期的多行中的值为5,我认为我必须改用Tolist()。 也许像这样:

var room = (from u in db.Reservation
            where u.RoomId == roomId
            select u  
           ).Tolist();

问题:

如何检查 每个 roomId的值为5,然后防止在同一房间中重叠日期?

我尝试了以下操作,但有时不起作用...

foreach(var item in room)
{
  if((StartDateWantToBook <= item.EndDate) && (item.StartDate <= EndDateWantToBook))
  {
       overlaps = true;
       MessageBox.Show("This room is already reserved");
  }
  else
  {
      // Process to reserv this room
      overlaps = false;
  }

2 个答案:

答案 0 :(得分:2)

else块将overlaps设置为false。即使存在重叠的保留,如果它处理的最后一个保留不重叠,它也会被设置为false。摆脱else块。

答案 1 :(得分:1)

首先,请更改代码以提高可读性

bool overlaps = false;
foreach(var item in room)
{
  if((StartDateWantToBook <= item.EndDate) && ( EndDateWantToBook >= item.StartDate))
     {
        overlaps = true;
        MessageBox.Show("This room is already reserved");
        // or you could use break; here to exist 
     }
}
// you could continue here by checking if(overlaps)

使用此方法,您可以删除else块以减少一些编码行。