开发者

Possible to create a list of the last 12 months using LINQ?

I was hoping to do something like this:

        List<DateTime> last12 = new List<DateTime>(12);
        last12.ForEach(t=>t.AddMonths(-{t.In开发者_Python百科dex}));

But haven't quite figured out how to do the {t.Index} part...

Is such a thing possible?


 DateTime start = DateTime.Now; 
 List<DateTime> last12 = (from r in Enumerable.Range(1,12) select start.AddMonths(0-r)).ToList();


It's not clear if you want the current month counted are not, but this will point you in the right direction which you can edit accordingly for your needs.

DateTime now = DateTime.Now;
DateTime currentMonth = new DateTime(now.Year, now.Month, 1);
var lastTwelveMonths = 
    Enumerable.Range(0, 12)
              .Select(i => -i)
              .Select(monthsToAdd => currentMonth.AddMonths(monthsToAdd))
              .ToList();


Foreach is tecnically not a Linq-method. It exists as a concrete method in the List class, but not in any interface.

var now = DateTime.Now;
var months = Enumerable.Range(1, 12).Select(n => now.AddMonths(-n));

foreach (var month in months)
{
   Console.WriteLine(month.ToString("MMMM"));
}

Produces (in danish)

november
oktober
september
august
juli
juni
maj
april
marts
februar
januar
december
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜