1

I have a table in my database that looks a bit like this:

Links

LinksID

TvID(foreign Key)

Season

Episode

Link

Now I'm trying to have a foreach statement in my view so that it will look something like this on my page.

Season 1

Episode 1

Episode 2

Episode 3

Season 2

Episode 1

Episode 2

Episode 3

However all I can get is

Season 1 Episode 1

Season 1 Episode 2

Season 1 Episode 3

Season 2 Episode 1

Season 2 Episode 2

Season 2 Episode 3

So after some googling I have now got my foreach like this however it obviously only display the first episode which is not what I'm after.

@foreach (var item in Model.Links.GroupBy(x => x.Season).Select(s => s.First()))
{
<p>Season @Html.DisplayFor(modelItem => item.Season) @Html.DisplayFor(modelItem => item.Episode)</p>
}

what am I doing wrong?

niko619
  • 433
  • 9
  • 20
  • 1
    - have you tried @foreach (var item in Model.Links.GroupBy(x => x.Season).Select(s => s)). - Or you can create a Dictionary where the Key is the season, and the value is all the episodes of that season. – Omar.Alani Oct 27 '14 at 03:23
  • If I use the foreach you mentioned I get this error `'System.Linq.IGrouping' does not contain a definition for 'Season' and no extension method 'Season' accepting a first argument of type 'System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)`. How would I create the dictionary idea as I have never done that before – niko619 Oct 27 '14 at 03:30

2 Answers2

3

You want something like this:

@{
    var myList = Model.Links
        .GroupBy(x => x.Season)
        .Select(x => new { Season = x.Key, Episodes = x });
}
@foreach (var season in myList)
{
   <strong>Season @Html.DisplayFor(modelItem => season.Season)</strong>
   foreach(var episode in season.Episodes)
   {
        @Html.DisplayFor(modelItem => item.Episode)
   }
}
DLeh
  • 23,806
  • 16
  • 84
  • 128
  • Yes that worked, thank you. Just so I understand better what does this section actually do? `Select(x => new { Season = x.Key, Episodes = x });` – niko619 Oct 27 '14 at 03:38
  • you specify what you're selecting from the grouping that you're interested in. in this case, you need to know what season it is (so you select `x.Key`, "Season", which was key you used for grouping). The other thing you need is the results of the grouping, which is the actual episodes. So then you enumerate through each season, and then enumerate each episode in the grouped season. This will probably help: http://stackoverflow.com/questions/7325278/group-by-in-linq – DLeh Oct 27 '14 at 03:41
1

You just try this code

            @foreach (var item in Model.Links.GroupBy(x => x.Season).tolist()))
    {
    Season @Html.DisplayFor(modelItem => item.Season) 

    @foreach (var items in Model.Links.where(z=>z.season==itme.season))

    {
            @Html.DisplayFor(modelItem => item.Episode)
    }
    } 
diy
  • 119
  • 1
  • 1
  • 10