简体   繁体   中英

Linq to Entities Group By where there are some groups with no elements

Model classes:

public class Video
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime ReleasedDate { get; set; }
    public byte GenreId { get; set; }
    public Genre Genre { get; set; }
    public Classification Classification { get; set; }
    public IList<Tag> Tags { get; set; }
}

public class Genre
{
    public byte Id { get; set; }
    public string Name { get; set; }
    public IList<Video> Videos { get; set; }
}

For example Genre Names are: Action, Drama, Comedy and Horror. There are no videos for Comedy and Horror genre.

View Model Class:

public class CountOfVideos
{
    public string Classification { get; set; }
    public int NumberOfMovies { get; set; }
}

Controller Class:

 public ActionResult Movies()
    {
        var movies = _context.Videos
            .GroupBy(v => v.Genre.Name)
            .Select(g => new CountOfVideos { Classification = g.Key, NumberOfMovies = g.Count() })
            .ToList();

        return View(movies);
    }

View:

@model IEnumerable<LinqTest.ViewModels.CountOfVideos>

<table class="table table-bordered table-hover">
<thead>
    <tr>
        <th>Name</th>
        <th>Count</th>
    </tr>
</thead>
<tbody>
    @foreach (var movie in Model)
    {
        <tr>
            <td>@movie.Classification</td>
            <td>@movie.NumberOfMovies</td>
        </tr>
    }
</tbody>

Code works correctly but it doesn't show names of the genres where there are no videos in them. View generates something like:

Action 23 Drama 15 but I'd like to generates Action 23 Drama 15 Comedy 0 Horror 0.

You should start from the collection holding the base data you need. In this case: Genres.

Something like:

 public ActionResult Movies() {
  var genres = _context.Genres
   .Select(g => new CountOfVideos {
    Classification = g.Name, NumberOfMovies = g.Videos.Count()
   })
   .OrderBy(c => c.NumberOfMovies)
   .ToList();

  return View(genres);
 }

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