Linq列出了全年的月份+年份

Ali*_*san 3 c# linq

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

从当月开始

   var currentdate = System.DateTime.Now
Run Code Online (Sandbox Code Playgroud)

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

2011年12月2012年1月...... 2012年11月

Ant*_*lev 8

var months = 
    Enumerable.Range(0, 12).
    Select(n => DateTime.Today.AddMonths(n)).
    Select(d = new { Year = d.Year, Month = d.Month });
Run Code Online (Sandbox Code Playgroud)


mad*_*dd0 6

我正在编辑将我的示例代码转换为我可能在生产中几乎使用的方法,因为它更可测试且具有文化感知:

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
           };
}
Run Code Online (Sandbox Code Playgroud)

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

LINQPad输出