根据当前星期几对星期几进行排序

Sorting days of the week based based on current day of the week

我正在尝试使用 C# 中的 DayOfWeek 枚举对星期几进行排序,使用 Linq,使用以下代码片段-

DayOfWeek currentDayOfWeek = DateTime.UtcNow.DayOfWeek;

SortedDictionary<DayOfWeek, TimeSpan> backupSchedule = 
    new SortedDictionary<DayOfWeek, TimeSpan>();

Dictionary<DayOfWeek, TimeSpan> sortedScheduleBasedOnCurrentDayOfWeek 
    = new Dictionary<DayOfWeek, TimeSpan>();

sortedScheduleBasedOnCurrentDayOfWeek = backupSchedule.OrderBy(
    backupdayandtime => (((int)backupdayandtime.Key + (int)currentDayOfWeek) % 7))
    .ToDictionary(t => t.Key, t => t.Value);

如果当前DayOfWeekWednesday, backupSchedule 中的天数列表是

Friday
Thursday
Wednesday

我希望上面的结果是

Wednesday
Thursday
Friday

然而,上面的代码导致

Thursday
Friday
Wednesday

我是不是漏掉了什么?

((int)backupdayandtime.Key + (int)currentDayOfWeek) % 7)

应该是 - 而不是 +。

假设今天是星期三,也就是 3。那么星期二就是 2,2 - 3 = -1,-1 mod 7 就是 6。星期三就是 (3-3) mod 7 即 0。星期四将是 (4-3) mod 7 即 1.

有了加号,您会得到星期二 = 5、星期三 = 6、星期四 = 0 等,这就是您最终得到的顺序。

请尝试 运行 这个 LINQ 命令。

sortedScheduleBasedOnCurrentDayOfWeek = backupSchedule.OrderBy(backupdayandtime => (((int)backupdayandtime.Key >= (int)currentDayOfWeek)? ((int)backupdayandtime.Key - (int)currentDayOfWeek) : (((int)backupdayandtime.Key + 7) - (int)currentDayOfWeek))).ToDictionary(t => t.Key, t => t.Value);

首先,我使用的排序是

backupSchedule
    // This lambda evaluates to `true` for e.g. Sunday through Tuesday;
    // `true > false` therefore these days will appear last
    .OrderBy(kvp => kvp.Key < currentDayOfWeek)
    // This then sorts each half in the normal order - not really
    // necessary if the original source is already in the normal order
    .ThenBy(kvp => kvp.Key)

其次,您不能真正将序列存储在字典中并期望字典记住您输入的顺序。在这种情况下似乎可行,但是没有保证它会。

您无法将结果存储在字典中 - 只需将键按顺序存储在数组中(或直接在 foreach 中使用),然后使用原始字典查找值。