Home > Back-end >  Selecting all 12 month datetimes for a given year
Selecting all 12 month datetimes for a given year

Time:09-29

I'm selecting an IEnumerable of DateTime by using a list of int which represent a year.

Each of the resulting DateTimes is given a default month and day of 1 so e.g.

List<int> years = new List<int>() { 2018, 2017, 2016 };
var dateTimes = years.Select(x => new DateTime(int.Parse(x), 1, 1));

Gives me 2018/01/01, 2017/01/01, 2016/01/01 (ignoring the time component)

I want to get the same results but for each month of each year too, so actually 36 results for three given years:

2018/01/01
2018/02/01
... 
2018/11/01
2018/12/01
2017/01/01
...
2016/12/01

(this is using non-US culture datetime where months are the middle value)

I was wondering if C# had a really nice shortcut like the range notation

var dateTimes = years.Select(x => new DateTime(int.Parse(x), 1..12, 1));

But that certainly doesn't work.

Any syntactic-shortcut way to achieve this without just looping i = 1 to 12 style?

The best I came up with was:

var dateTimes = new List<DateTime>();
foreach(var y in years)
{
    for (int i = 1; i <= 12; i  ) dateTimes.Add(new DateTime(int.Parse(y), i, 1));
}

Which does exactly what I want but though there was a more succinct way to write.

CodePudding user response:

  var dateTimes = years.SelectMany(y => Enumerable.Range(1, 12).Select(m => new DateTime(y, m, 1))); // .ToList() if you want
  • Related