开发者

Nested foreach Loops on a Webpage

I am selecting the following data from an SQL database table in my controller

            var fixtures = from f in _context.Fixtures
                       where f.MatchDate.Year == year &&
                       (gender.Contains( f.Gender )) &&
                       (type.Contains( f.MatchType )) &&
                       (team.Contains( f.TeamName ))
                       orderby f.TeamName, f.MatchDate
                       select f;

        return View( "DisplayLeagues", fixtures.ToList() );

and calling the DisplayLeagues view to display it. As you can see from the orderby, it contains more tha开发者_Go百科n one team. I want to display a separate table on the webpage for each team. My page declaration contains

Inherits="System.Web.Mvc.ViewPage<IEnumerable<RLSBCWebSite.Domain.Entities.Fixture>>"

as the declaration of the Model. To display the individual lines of the table, I have

<% foreach (var item in Model.AsEnumerable()) { %>

But how do I add a loop control based on the name of the team around the table as a whole? It doesn't seem possible to code

<% foreach (var team in Model.TeamName ....


Something like:

group g by f.TeamName into tmp
select new {TeamName  = f.Key, Fixtures = tmp.ToList() }

this will give you one group per team, i.e.

foreach(var grp in query) {
    Console.WriteLine(grp.TeamName);
    foreach(var fixture in grp.Fixtures) {
       // write fixture details
    }
}

Note that this changes each item to an IGrouping<string, List<Fixture>>, and note that ToLookup will do something very similar if that is easier.


For the outer loop, which produces a separate table for each team, I used the following

<% foreach (var teamName in Model.AsEnumerable().GroupBy( r => r.TeamName )) {

For the inner loop, which produces the individual matches for each team, I used

<% foreach (var item in Model.AsEnumerable().Where(item => item.TeamName == teamName.Key.ToString())) {

This works very well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜