How To Generate The Last Date Of Every Month Of A Year With LINQ In C# & .NET
[C#, .NET, LINQ]
I recently need to generate the last day of each month, for some processing in an algorithm.
The default goto would be this:
public IEnumerable<DateOnly> GetDatesInYear(int year)
{
var temp = new DateOnly(year, 1, 1);
while (temp.Year == year)
{
yield return temp.AddMonths(1).AddDays(-1);
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, DateTime.DaysInMonth(year, x)));
}
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!