3

I've got a C# class I'm working with representing a profile that includes some scheduling information indicating how many updates during the day, and which days to update with boolean values for each day of the week. I've seen some posts here and on other sites to find the next instance of a given weekday, etc. but not something where which days one is looking for can vary.

For example, I might be given an object with Monday, Wednesday, and Thursday as true. What's the best way to find the next instance of the next true day of the week?

I can think of some long and drawn out ways to find the next "true" day of the week, but is there something cleaner built in that I'm unfamiliar with that would do the trick? I'd prefer not to use any third party libraries, as that requires lots of special approval from information assurance folks.

UtopiaLtd
  • 2,520
  • 1
  • 30
  • 46

1 Answers1

9

Given that it's hardly going to take a long time to loop, that's going to be the simplest approach:

DateTime nextDay = currentDay.AddDays(1);
while (!profile.IsActive(nextDay.DayOfWeek))
{
    nextDay = nextDay.AddDays(1);
}

(That's assuming you've already validated that the profile is active on at least one day... otherwise it'll loop forever.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @rpax: Faster and *far* less readable. Fine for micro-optimization if it's been *proven* to be a bottleneck, but I wouldn't do it otherwise. – Jon Skeet Mar 10 '14 at 17:40
  • me neither. At the beginning of the question it's explained – rpax Mar 10 '14 at 17:42
  • @rpax: Yes, but that's on that question, not on this one :) Still, I may well see whether I can adapt your code for Noda Time, if you're happy for me to do so... – Jon Skeet Mar 10 '14 at 17:43