Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a delegate extension method in c#?

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.

like image 883
Matthew Avatar asked Jan 30 '26 04:01

Matthew


1 Answers

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);
like image 123
Ani Avatar answered Feb 01 '26 20:02

Ani