0

我正在尝试创建一个存档,括号内是每月的项目数,我想出了这样的东西:-

@{
  var startMonth = DateTime.Now.Month;
  var startYear = DateTime.Now.Year;
  var blogList = Model.BlogViewModel.BlogArchiveList;
  var monthName = DateTime.Now.ToString("MMMM");
  var Counter = 0;
}
@foreach (var item in blogList)
{
  if (item.BlogDate.Year == startYear)
  {
      if (item.BlogDate.Month == startMonth)
      {
          Counter = Counter + 1;
      }
      else
      {
          Counter = 1;
          startMonth = item.BlogDate.Month;
      }
  }
  else
  {
      Counter = 1;
      startYear = item.BlogDate.Year;
      startMonth = item.BlogDate.Month;
  }
  monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(startMonth);
  @Html.ActionLink(monthName + " " +  startYear + "("+ Counter +")", "Archive", new  
  {
     year=startYear, month=startMonth}) <br/>
  }

尽管这似乎可行,但如果有多个条目,我会多次写入月份。

如何避免多次写入该月,同时仍获得该月的帖子数?

感谢您的帮助和时间

4

1 回答 1

1

尝试使用下一个代码:

var statistics = 
     blogList.GroupBy(val => new {val.BlogDate.Month, val.BlogDate.Year})
             .OrderBy(item => item.Key.Year)
             .ThenBy(item => item.Key.Month)
             .Select (grouped => new {Month = grouped.Key.Month, Year = grouped.Key.Year, Count = grouped.Count() });

foreach (var item in statistics)
{
    var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.Month);
    Console.WriteLine (string.Format("{0} {1} ({2})", monthName, item.Year, item.Count));   
}

打印正确的结果,例如

December 2012 (3)
January 2013 (4)
于 2013-01-09T17:24:31.787 回答