简体   繁体   中英

Most elegant way to morph this sequence

I've got the Day of the week stored in a database table (that I do not control), and I need to use it in my code.

Problem is, I want to use the System.DayOfWeek enum for representation for this, and the sequences are not the same.

In the database, it's as follows:

1  2  3  4  5  6  7
S  M  T  W  T  F  S

I need it as follows:

0  1  2  3  4  5  6
M  T  W  T  F  S  S

What's the most elegant way to do this?

for example, I could do:

i = dayOfWeek;
i = i - 2;
if (i < 0) {
    i = 6;
}

but that's a bit inelegant. Any suggestions?

<EDIT>

Ahem. Apparently (.net reflector says) DayOfWeek is 0 indexed starting with Sunday.

Always read the docs before asking daft questions.

However, I'm still interested in an answer, just to satisfy my own curiosity, so go for it.

</EDIT>

The value you want is

(DayOfWeek)((dbDay + 5) % 7)

using the modulo operator % .

Wrap it in a function:

public int DbToDayOfWeek(int dbDay)
{
   if (dbDay == 1)
     return 6;

   return dbDay  -2;

}

Or:

public DayOfWeek DbToDayOfWeek(int dbDay)
{
   if (dbDay == 1)
     return DayOfWeek.Sunday;

   return (DayOfWeek)(dbDay - 2);

}

Although I can't imagine the values changing, you should really avoid assuming that the DayOfWeek enumerated values will stay the same - so code accordingly.

static DayOfWeek[] _toDaysTable = new DayOfWeek[] {
    DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday,
    DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday
};

static DayOfWeek ToDayOfWeek(int myDayOfWeek)
{
     int index = myDayOfWeek - 1;
     if (index < 0 || index >= _toDaysTable.Length)
          throw new ArgumentOutOfRangeException("myDayOfWeek");
     return _toDaysTable[index];
}

static int FromDayOfWeek(DayOfWeek day)
{
    int index = Array.IndexOf(_toDaysTable, day);
    if (index < 0)
        throw new ArgumentOutOfRangeException("day");
    return index + 1;
}

You could just create your own enum and map the enum directly to the value in the database

public enum DayOfWeek
{
    Mon = 2,
    Tue = 3,
    Wed = 4,
    Thu = 5,
    Fri = 6,
    Sat = 7,
    Sun = 1
}

Then you could use an extension method of your DayOfWeek type to retrieve the value:

public static int ToInt(this DayOfWeek dow)
{
    return (int)dow;   
}

Unless you are relying on the DayOfWeek for actual comparisons with Dates, otherwise you will have to do the conversion between the offsets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM