月份和年份列表

时间:2013-01-09 17:20:51

标签: c# asp.net-mvc linq razor asp.net-mvc-4

我正在尝试使用括号内每月的项目数创建一个档案,我想出了这样的事情: -

@{
  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/>
  }

虽然这似乎有效,但如果有多个条目,我会多次写月份。

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

感谢您的帮助和时间

1 个答案:

答案 0 :(得分: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)