How To Generate The First Day Of Every Month Of A Year With LINQ In C# & .NET
[C#, .NET, LINQ]
I recently need to generate the first day of each month, for some processing in an algorithm.
The default goto would be this:
public IEnumerable<DateOnly> GetDatesInYear(int year)
{
var start = new DateOnly(year, 1, 1);
var temp = start;
while (temp.Year == year)
{
yield return temp;
temp = temp.AddMonths(1);
}
}
Straightforward enough.
You can also achieve the same thing using a LINQ expression.
public IEnumerable<DateOnly> GetDatesInYear(int year)
{
return Enumerable.Range(1, 12).Select(x => new DateOnly(year, x, 1));
}
This can be visualized with this harness:
var year = 2026;
foreach (var date in GetDatesInYear(year))
{
Console.WriteLine(date);
}

The code is in my GitHub.
Happy hacking!