I have a collection of objects that I need to iterate through and do stuff with. Seems easy so far. However, I have some conditions which is making it rather complicated.
Here is some info:
The collection contains a bunch of "Planet" objects which have planetary phase times.
Planetary viewing times are combined into blocks if the time span between 2 phases is less than or equal to 30 minutes.
For example, here are 6 phase times:
- Phase 1: 8:00am - 9:30am
- Phase 2: 10:00am - 11:00am
- Phase 3: 11:20am - 12:30pm
- Phase 4: 2:00pm - 4:00pm
- Phase 5: 6:30pm - 7:30pm
- Phase 6: 7:45pm - 9:00pm
With the data above, we have the following blocks:
- Phase 1 through Phase 3: one continuous viewing block
- Phase 4: separate viewing block
- Phase 5 and Phase 6: one continuuous viewing block
Math:
- (Phase 2 starting time) - (Phase 1 ending time) = 30 minutes
- (Phase 3 starting time) - (Phase 2 ending time) = 20 minutes
- (Phase 4 starting time) - (Phase 3 ending time) = 90 minutes
- (Phase 5 starting time) - (Phase 4 ending time) = 150 minutes
- (Phase 6 starting time) - (Phase 5 ending time) = 15 minutes
My failed attempt thus far:
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++;
}
I've spent hours on this stupid loop and I think another set of eyes would do it good.
It feels/looks too complex, too old-fashioned, and too confusing. Is there a better/modern way of doing this?
Thanks!