简体   繁体   中英

MVC Foreach distinct value from database

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM