user348173
user348173

Reputation: 9278

Collating results in a table in MVC

I have a following 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); }
    }
}

In the controller I wrote:

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

in a view:

<% 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>
                <% } %>

The result is:

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

But I want that was:

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

Thanks.

Upvotes: 1

Views: 114

Answers (1)

Lukazoid
Lukazoid

Reputation: 19416

You want to perform a GroupBy on cinema.

Make sure System.Linq is listed as a using in your view. And then you can do the following:

<% 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>
<% } %>

Upvotes: 2

Related Questions