改变这个序列的最优雅的方式
我已将一周中的某一天存储在数据库表中(我无法控制),并且我需要在代码中使用它。
问题是,我想使用 System.DayOfWeek 枚举来表示这一点,并且序列不相同。
在数据库中,如下:
1 2 3 4 5 6 7
S M T W T F S
我需要如下:
0 1 2 3 4 5 6
M T W T F S S
执行此操作最优雅的方法是什么?
例如,我可以这样做:
i = dayOfWeek;
i = i - 2;
if (i < 0) {
i = 6;
}
但这有点不优雅。有什么建议吗?
<编辑>
咳咳。显然(.net 反射器说)DayOfWeek 的索引为 0,从星期日开始。
在问愚蠢的问题之前一定要先阅读文档。
不过,我还是对答案感兴趣,只是为了满足自己的好奇心,所以就去吧。
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想要的值
使用模运算符
%
。The value you want is
using the modulo operator
%
.将其包装在一个函数中:
或者:
Wrap it in a function:
Or:
尽管我无法想象这些值会发生变化,但您确实应该避免假设 DayOfWeek 枚举值将保持不变 - 因此进行相应的编码。
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.
您可以创建自己的枚举并将枚举直接映射到数据库中的值
然后您可以使用
DayOfWeek
类型的扩展方法来检索值:除非您依赖于
DayOfWeek
用于与日期进行实际比较,否则您将必须在偏移量之间进行转换。You could just create your own enum and map the enum directly to the value in the database
Then you could use an extension method of your
DayOfWeek
type to retrieve the value:Unless you are relying on the
DayOfWeek
for actual comparisons with Dates, otherwise you will have to do the conversion between the offsets.