DayOfWeek will receive the next DayOfWeek (Monday, Tuesday ... Sunday)

Is there a way to summarize this code on 1-2 lines?

My goal is to return, for example, I have DayOfWeek, which on Monday, I want to receive the next day (Tuesday) or n days after that.

switch (_RESETDAY) { case DayOfWeek.Monday: _STARTDAY = DayOfWeek.Tuesday; break; case DayOfWeek.Tuesday: _STARTDAY = DayOfWeek.Wednesday; break; case DayOfWeek.Wednesday: _STARTDAY = DayOfWeek.Thursday; break; case DayOfWeek.Thursday: _STARTDAY = DayOfWeek.Friday; break; case DayOfWeek.Friday: _STARTDAY = DayOfWeek.Saturday; break; case DayOfWeek.Saturday: _STARTDAY = DayOfWeek.Sunday; break; case DayOfWeek.Sunday: _STARTDAY = DayOfWeek.Monday; break; default: _STARTDAY = DayOfWeek.Tuesday; break; } 
+5
source share
5 answers

This is just an int listing, starting from Sunday (0) to Saturday (6), according to MSDN:

The DayOfWeek enumeration is a day of the week on calendars that have seven days a week. The value of the constants in this enumeration ranges from DayOfWeek.Sunday to DayOfWeek.Saturday. If distinguished from the whole, its value varies from zero (which indicates DayOfWeek.Sunday) to six (which indicates DayOfWeek.Saturday).

So simple math should do this:

 DayOfWeek nextDay = (DayOfWeek)(((int)_RESETDAY + 1) % 7); 

Replace + 1 with + n if you need it.

+10
source

Yes.

 (DayOfWeek)((int)(_RESETDAY+1)%7) 
+4
source

same result as append and modulo material mentioned above but more readable by imho:

 day = (day == DayOfWeek.Saturday) ? DayOfWeek.Sunday : day + 1; 

The obvious intent of the code is always nicer.

+2
source
  static DayOfWeek dayplus (DayOfWeek day) { if (day == DayOfWeek.Saturday) return DayOfWeek.Sunday; else return day + 1; } 

for instance

 Console.WriteLine(dayplus(DayOfWeek.Sunday)); 

Will be back on monday

0
source

In general, the solution uses modulo arithemtics:

  DayOfWeek _RESETDAY = ...; int shift = 1; // can be positive or negative // + 7) % 7 to support negative shiftΒ΄s DayOfWeek result = (DayOfWeek) ((((int)_RESETDAY + shift) % 7 + 7) % 7); 

Probably the best incarnation is to hide the combinatorial formula in the extension method:

  public static class DayOfWeekExtensions { public static DayOfWeekShift(this DayOfWeek value, int shift) { return (DayOfWeek) ((((int)value + shift) % 7 + 7) % 7); } } ... var result = _RESETDAY.Shift(1); 

and slightly reduced (only works in all cases if the negative shift is not lower than -7):

  return (DayOfWeek)(((int)value + shift + 7) % 7); 
0
source

Source: https://habr.com/ru/post/1232471/


All Articles