Abe Miessler
Abe Miessler

Reputation: 85126

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

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

Is such a thing possible?

Upvotes: 0

Views: 1354

Answers (3)

Pauli &#216;ster&#248;
Pauli &#216;ster&#248;

Reputation: 6916

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

Upvotes: 1

sgmoore
sgmoore

Reputation: 16077

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

Upvotes: 3

jason
jason

Reputation: 241789

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

Upvotes: 1

Related Questions