可以使用 LINQ 创建过去 12 个月的列表吗?

发布于 2024-10-07 01:53:23 字数 234 浏览 0 评论 0原文

我希望做这样的事情:

        List<DateTime> last12 = new List<DateTime>(12);
        last12.ForEach(t=>t.AddMonths(-{t.Index}));

但还没有完全弄清楚如何做 {t.Index} 部分...

这样的事情可能吗?

I was hoping to do something like this:

        List<DateTime> last12 = new List<DateTime>(12);
        last12.ForEach(t=>t.AddMonths(-{t.Index}));

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

Is such a thing possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撧情箌佬 2024-10-14 01:53:23
 DateTime start = DateTime.Now; 
 List<DateTime> last12 = (from r in Enumerable.Range(1,12) select start.AddMonths(0-r)).ToList();
 DateTime start = DateTime.Now; 
 List<DateTime> last12 = (from r in Enumerable.Range(1,12) select start.AddMonths(0-r)).ToList();
執念 2024-10-14 01:53:23

目前尚不清楚您是否希望计算当前月份,但这将为您指明正确的方向,您可以根据需要进行相应的编辑。

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

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();
手长情犹 2024-10-14 01:53:23

从技术上讲,Foreach 不是 Linq 方法。它作为 List 类中的具体方法存在,但不存在于任何接口中。

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

农产品(丹麦语)

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文