【问题标题】:Linq list for month+year for the whole year全年的月+年Linq列表
【发布时间】:2011-12-19 18:53:11
【问题描述】:

寻找 linq 查询以填充带有月份 + 年份的列表,例如(2012 年 1 月)

从当月开始

   var currentdate = System.DateTime.Now

如果 2011 年 12 月是当前月份 那么列表应该是这样的

2011 年 12 月 2012 年 1 月 …… 2012 年 11 月

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    var months = 
        Enumerable.Range(0, 12).
        Select(n => DateTime.Today.AddMonths(n)).
        Select(d = new { Year = d.Year, Month = d.Month });
    

    【讨论】:

      【解决方案2】:

      我正在编辑以将我的示例代码变成一种我几乎可以在生产中使用的方法,因为它更易于测试和文化意识:

      public IEnumerable GetMonths(DateTime currentDate, IFormatProvider provider)
      {
          return from i in Enumerable.Range(0, 12)
                 let now = currentDate.AddMonths(i)
                 select new
                 {
                     MonthLabel = now.ToString("MMMM", provider),
                     Month = now.Month,
                     Year = now.Year
                 };
      }
      

      此输出(在法国计算机上):

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 2013-02-12
        相关资源
        最近更新 更多