I have a list of objects in C# with "BeginDate" and "EndDate" DateTime properties. I need to create a new list of these objects with all the objects consolidated when the BeginDate of one object matches the EndDate of the previous one within 24 hours, going back until there is a break longer than 24 hours.
For example. I have a list like so
BeginDate EndDate
Object 1 12/21/2017 01/20/2018
Object 2 12/01/2017 12/21/2017
Object 3 10/25/2017 12/01/2017
Object 4 09/17/2017 10/25/2017
Object 5 08/01/2017 09/02/2017
Object 6 06/25/2017 07/26/2017
Object 7 04/20/2017 06/25/2017
that needs to be turned into a list like this
BeginDate EndDate
Object 1 09/17/2017 01/20/2018
Object 2 08/01/2017 09/02/2017
Object 3 4/20/2017 07/26/2017
My issue is further exacerbated by the fact that if the Object represents an ongoing project, then the EndDate might be a null value. So the original developers chose to use a DateTime? type instead of a regular DateTime value for that field. So you could have a situation where you have
BeginDate EndDate
Object 1 12/21/2017 null
Object 2 12/01/2017 12/21/2017
which would have to be converted to either
BeginDate EndDate
Object 1 12/01/2017 null
or
BeginDate EndDate
Object 1 12/01/2017 (DateTime.Now)
Right now, I'm trying this but it's not completely consolidating all the objects:
for (var index = 0; index < ProjectList.Count; index++)
{
Project_BL ThisProject = ProjectList[index];
Project_BL nextProject = ProjectList[index + 1];
if (index + 1 < ProjectList.Count && ProjectList[index+1] != null)
{
DateTime TempEndDate = nextProject.EndDate ?? DateTime.Now;
TimeSpan DifferenceBetweenProjectsTimespan =
ThisProject.BeginDate.Subtract(TempEndDate);
int DifferenceBetweenProjects = (int)DifferenceBetweenProjectsTimespan.TotalHours;
if (DifferenceBetweenProjects <= 24)
{
if (IsLongProject == true)
{
nextProject.ProjectNature = "Long-term";
}
nextProject.EndDate = ThisProject.EndDate;
ProjectList.RemoveAt(index);
continue;
}
else
{
ProjectList.Add(ThisProject);
index++;
continue;
}
}
else
{
ProjectList.Add(ThisProject);
}
}
return ProjectList;
Anyone have any ideas? I'm banging my head against the wall at this point. So any help would be appreciated.