简体   繁体   English

月份和年份列表

[英]list of months and years

I am trying to create an Archive, with the number of items per month inside parenthesis, and I have come up with something like this:- 我正在尝试创建一个存档,每个括号内每个月的项目数,并且我想出了类似以下内容:

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

Although this seems to work, I am getting the month written multiple times if there is more than one entry. 尽管这似乎可行,但如果有多个条目,我将多次写入该月份。

How can I avoid writing the month multiple times, while still getting the count of posts for that month? 我如何避免多次写一个月,同时仍然获得该月的帖子数?

Thanks for your help and time 感谢您的帮助和时间

Try to use next code: 尝试使用下一个代码:

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));   
}

Prints correct results, for example 打印正确的结果,例如

December 2012 (3)
January 2013 (4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM