c#:组合for(each)循环生成高效代码
本文关键字:循环 高效 代码 each 组合 for | 更新日期: 2023-09-27 18:15:41
这是我的时间表代码的一部分
两个问题:
-
我如何防止必须循环通过时间,然后房间预订检查它是否存在于给定的时间段。
是否有一种方法只是说"这次,这个列表中是否有匹配项及其Id是什么"
无论如何,我可以将外部td设置为类渐变,而不是span。(请注意,在一个时间段内可能有多个预订,因此将td排除在foreach循环之外)
<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>
}
这样怎么样
@foreach (var roombooking in ViewBag.RoomBookings.Where( /* in range */ ))
这样你就可以删除第一个for循环
试试这样做。
<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>
它只循环
您应该在控制器中过滤数据,并且只将相关数据传递给视图。
您可以使用linq来处理控制器中的对象,甚至可以更好地过滤数据库中的数据