【发布时间】:2016-07-22 16:56:18
【问题描述】:
我有一组需要迭代和处理的对象。到目前为止似乎很容易。但是,我有一些条件使它变得相当复杂。
这里有一些信息:
该集合包含一堆具有行星相位时间的“行星”对象。
如果两个阶段之间的时间跨度小于或等于 30 分钟,则将行星观看时间组合成块。
例如,这里有 6 个阶段时间:
- 第一阶段:上午 8:00 - 上午 9:30
- 第 2 阶段:上午 10:00 - 上午 11:00
- 第三阶段:上午 11:20 - 下午 12:30
- 第 4 阶段:下午 2:00 - 下午 4:00
- 第 5 阶段:下午 6:30 - 晚上 7:30
- 第 6 阶段:晚上 7:45 - 晚上 9:00
根据上面的数据,我们有以下几块:
- 第 1 阶段到第 3 阶段:一个连续的观察块
- 第 4 阶段:单独的查看块
- 第 5 阶段和第 6 阶段:一个连续的观察块
数学:
- (第 2 阶段开始时间)-(第 1 阶段结束时间)= 30 分钟
- (第 3 阶段开始时间)-(第 2 阶段结束时间)= 20 分钟
- (第 4 阶段开始时间)-(第 3 阶段结束时间)= 90 分钟
- (第 5 阶段开始时间)-(第 4 阶段结束时间)= 150 分钟
- (第 6 阶段开始时间)-(第 5 阶段结束时间)= 15 分钟
到目前为止我的失败尝试:
int i = 0;
bool continueBlocking = false;
foreach (var p in GalaxySector) //IEnumerable
{
//ensure that dates are not null
if (p.StartDatePhase != null || p.EndDatePhase != null) {
if (continueBlocking) {
string planetName = p.Name;
string planetCatalogId = p.CatalogId;
datetime? StartPhase = p.StartDatePhase.Value;
datetime? EndPhase = p.EndDatePhase.Value;
} else {
string planetName = p.Name;
string planetCatalogId = p.CatalogId;
datetime? StartPhase = p.StartDatePhase.Value;
datetime? EndPhase = p.EndDatePhase.Value;
}
if (i < 2) {
continue;
}
TimeSpan? spanBetweenSections = StartPhase - EndPhase;
if ( spanBetweenSections.Value.TotalMinues <= 30) {
continueBlocking = true;
continue;
} else {
CreateSchedule(planetName, planetCatalogId, StartPhase, EndPhase);
continueBlocking = false;
}
}
i++;
}
我已经在这个愚蠢的循环上花费了几个小时,我认为另一双眼睛会做得很好。
感觉/看起来太复杂、太老套、太混乱了。有没有更好/现代的方法来做到这一点?
谢谢!
【问题讨论】:
-
午夜后相位会循环吗?也就是说
12:15am - 2:30am和10:00pm - 11:50pm是否构成一次观看? -
如果 continueBlocking 做 X,否则做 X。X = X。那你为什么要使用 continueBlocking ?
-
您是否考虑过使用 case 语句而不是多个 if 语句?
标签: c# c#-4.0 foreach asp.net-4.5