I want to get all the dates between two endpoints using a provided frequency. So I'm basing my approach off this simple bit of code:
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
datesBetween.Add(date);
Now, I sometimes have a need to add days (as above), add months, or add years based on a FrequencyEnum
So I could use a switch and repeat the code 3 times for my uses, but I'm wondering if I can assign a delegate extension method rather than .AddDays or .AddMonths or .AddYears
Rather, I'd like to do something like this:
for (DateTime date = startDate; date <= endDate; date = date.AddFrequency)
datesBetween.Add(date);
where .AddFrequency is delegate defining the extension method needed for my frequency.
Alternatively, I could not use an extension method and simply use a function taking a date parameter and return as needed.
I think you want a Func<DateTime, DateTime>
Func<DateTime, DateTime> updater = d => d.AddFrequency(Frequency.Month);
for (DateTime date = startDate; date <= endDate; date = updater(date))
datesBetween.Add(date);
Of course, in your real code, your method would likely accept the delegate as an argument rather than initialize it on its own.
That said, with moreLinq, you could just do:
var datesBetween = startDate.Generate(date => date.AddDays(1))
.TakeWhile(date => date <= endDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With