21

我正在按他们的System.DayOfWeek属性订购一些对象。

DayOfWeek将 Sunday 视为一周的开始,而我希望它被订购以便它出现在end。它只是一个枚举,所以我无法修改它。但是我读到我可能能够创建一种自定义文化,但认为这可能是矫枉过正。

List<TimeBand> orderedTimeBands = timeBands.OrderBy(x => x.DayName).ToList()

也是DayNameDayOfWeek我想要orderedTimeBands从星期一 -> 星期日订购。

有任何想法吗?

4

2 回答 2

51

The simplest approach would be:

var orderedTimeBands = timeBands.OrderBy(x => ((int) x.DayOfWeek + 6) % 7)
                                .ToList()

So we have:

Name        Original value      Value after arithmetic
Sunday       0                  6
Monday       1                  0
Tuesday      2                  1
Wednesday    3                  2
Thursday     4                  3
Friday       5                  4
Saturday     6                  5

... which is what you want, I think.

于 2013-09-03T11:25:29.220 回答
11

我使用基于当前文化的解决方案:

// all days of week
var daysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>();

// get first day of week from current culture
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;

// all days of week ordered from first day of week
var daysOfWeekOrdered = daysOfWeek.OrderBy(x => (x - firstDayOfWeek + 7) % 7);

重要的部分是OrderBylambda。它基本上是上面乔恩答案的参数化版本

这样,它将在英国从周一开始订购,在美国从周日开始订购。

于 2016-10-10T16:52:15.667 回答