在MVC中对表进行排序

本文关键字:排序 MVC | 更新日期: 2023-09-27 18:23:49

我有以下BO:

public class CinemaSchedule 
{      
    private DateTime showDate;        
    public DateTime ShowDate
    {
        get { return showDate; }
        set { SetPropertyValue("ShowDate", ref showDate, value); }
    }
    private TimeSpan showTime;        
    public TimeSpan ShowTime
    {
        get { return showTime; }
        set { SetPropertyValue("ShowTime", ref showTime, value); }
    }
    private Cinema cinema; 
    public Cinema Cinema
    {
        get { return cinema; }
        set { SetPropertyValue("City", ref cinema, value); }
    }
}
 public class Cinema 
{
    private string code;       
    public string Code
    {
        get { return code; }
        set { SetPropertyValue("Code", ref code, value); }
    }
    private string name;        
    public string Name
    {
        get { return name; }
        set { SetPropertyValue("Name", ref name, value); }
    }
}

在控制器中,我写道:

model.Schedules = FilmRepository.GetById(eventId).CinemaSchedules;

在视图中:

<% foreach (var schedule in film.CinemaSchedules)
                { %>
                <tr>
                    <td><a href="#"><%=schedule.Cinema.Name%></a></td>
                    <td class="time_list">
                        <ul>
                            <li><a href="#"><%=TimeSpan.FromSeconds(schedule.ShowTime.Value) %></a></li>                            
                        </ul>
                    </td>
                </tr>
                <% } %>

结果是:

Cinema 1    19:00:00
Cinema 1    22:00:00
Cinema 2    19:00:00

但我想要的是:

Cinema 1     19:00:00     22:00:00
Cinema 2     19:00:00

谢谢。

在MVC中对表进行排序

您想要在影院上执行GroupBy

确保System.Linq在您的视图中列为使用。然后你可以做以下事情:

<% foreach (var scheduleGroup in film.CinemaSchedules.GroupBy(s => s.Cinema.Name))
{ %>
<tr>
    <td><a href="#"><%=scheduleGroup.Key%></a></td>
    <td class="time_list">
        <ul>
    <% foreach (var schedule in scheduleGroup)
    { %>
            <li><a href="#"><%=TimeSpan.FromSeconds(schedule.ShowTime.Value) %></a></li>                            
    <% } %>
        </ul>
    </td>
</tr>
<% } %>