按类型统计项目

时间:2017-03-14 09:45:00

标签: asp.net-mvc linq linq-to-sql

我正在尝试按类型计算项目以表示名称和&徽章计数,但它看起来像我遗失了一些东西 我的代码就像这样 在我的模型中:

  public Genre Genre { get; set; }
    [Required]
    public int GenreId { get; set; }

viewModel:

   public IEnumerable<LectureGig> UpcomingLectureGigs { get; set; }

控制器:

var upCommingLecture = _context.LectureGigs.Include(g => g.Artist).Include(g => g.Genre)
            .Where(g => (g.DateTime > DateTime.Now
                         && !g.IsCanceled ||
                         (g.IsWeekLy && (int) g.Days == (myDayOfWeek) || (int) g.Days >= 7)));

        var viewModel = new GigsViewModel
        {
            UpcomingLectureGigs = upCommingLecture.ToList().OrderBy(d => d.Days).ThenBy(g => g.GenreId),
            //remove for clear code
        };

        ViewBag.genre = viewModel.UpcomingLectureGigs.GroupBy(g => g.Genre.Name).Distinct();

和我的观点:

 @foreach (var gen in ViewBag.genre)
{
    <button type="button" class="btn btn-primary">@gen.Name <span class="badge"></span></button>
}

我得到的错误是:'string'不包含'Genre'的定义 感谢

1 个答案:

答案 0 :(得分:1)

你的意思:

ViewBag.genres = viewModel.UpcomingLectureGigs.GroupBy(g=>g.Genre.Name).Select(g=> new KeyValuePair<string, int>(g.Key,g.Count())).ToList();


 @foreach (var g in ViewBag.genres)
        {
            <button type="button" class="btn btn-primary">@g.Key<span class="badge">@g.Value
            </span></button>
        }

Working fiddle