C#:将(每个)循环组合到有效的代码中

时间:2011-11-24 10:38:22

标签: c# asp.net-mvc loops razor

这是我的时间表代码的一部分

两个问题:

  1. 如何防止必须遍历时间,然后检查房间检查以检查它是否存在于给定的时间段内。有没有办法只说“这个时候,这个列表中是否有匹配,它的ID是什么”

  2. 无论如何,我可以将外部td设置为类bgred,而不是跨度。 (请注意,时间段中可能有多个预订,因此将td从foreach循环中删除。)

  3. <tr>
        <th></th>
    
            @for (int i = 9; i <= 17; i++)
            {
            <th>@i:00</th>
            }
    </tr>
    
        @foreach (var RoomNo in ViewBag.Rooms)      
        {
    
            <tr>
    
                <th>@RoomNo</th>
    
               @for (int i = 9; i <= 17; i++)
               {
                   <td>
                   @foreach (var roombooking in ViewBag.RoomBookings)
                   {
                       DateTime DateCheckStart = DateTime.Parse(ViewBag.Date.ToShortDateString() + " " + i.ToString() + ":00");
                       DateTime DateCheckEnd = DateTime.Parse(ViewBag.Date.ToShortDateString() + " " + i.ToString() + ":59");
                       if (DateCheckStart < roombooking.EndDateTime && DateCheckEnd > roombooking.StartDateTime && roombooking.RoomNo == RoomNo)
                       {
                         <span class="bgred"> @roombooking.RentalNo</span>
                       }
                   }
                   </td>
               }
            </tr>
    
         }
    

3 个答案:

答案 0 :(得分:2)

这样的事情

@foreach (var roombooking in ViewBag.RoomBookings.Where( /* in range */ ))

这样你就可以删除你的第一个for循环

答案 1 :(得分:1)

您应该在控制器中过滤数据,只将相关数据传递给视图。

您可以将linq用于控制器中的对象,甚至可以更好地过滤数据库中的数据。

答案 2 :(得分:1)

尝试这样的事情。

 <table>
<tr>
    <th></th>

        @for (int i = 9; i <= 17; i++)
        {
        <th>@i:00</th>
        }
</tr>

@{ List<MyLibrary.MyRoomOccupancy> RoomBookingsTemp = ViewBag.RoomBookings;}

@foreach (var RoomNo in ViewBag.Rooms)
{
    <tr>
        <th>@RoomNo</th>

       @for (int i = 9; i <= 17; i++)
       {             
           DateTime DateCheckStart = DateTime.Parse(ViewBag.Date.ToShortDateString() + " " + i.ToString() + ":00");
           DateTime DateCheckEnd = DateTime.Parse(ViewBag.Date.ToShortDateString() + " " + i.ToString() + ":59");

           var sublist = (from RoomOcc in RoomBookingsTemp where DateCheckStart < RoomOcc.EndDateTime && DateCheckEnd > RoomOcc.StartDateTime && RoomOcc.RoomNo == RoomNo select RoomOcc);


           if (sublist.Count() > 0)
           {
              @Html.Raw("<td class= \"bgred\">");

            }
           else {
               Html.Raw("<td>");
           }

           foreach (var roombooking in sublist)
           {
               if (DateCheckStart < roombooking.EndDateTime && DateCheckEnd > roombooking.StartDateTime && roombooking.RoomNo == RoomNo)
               {
                  @roombooking.RentalNo
               }
           }
           @Html.Raw("</td>");

       }
    </tr>

}


</table>

这是做什么的,它只能通过他