Foad Shariat
Foad Shariat

Reputation: 37

C# Linq - Group by based on time difference in Start time and End Time

I have an object that looks like this:

[
{ StartTime: "05/21/2020 10:00", EndTime: "05/21/2020 10:30" },
{ StartTime: "05/21/2020 11:00", EndTime: "05/21/2020 11:30" },
{ StartTime: "05/21/2020 12:00", EndTime: "05/21/2020 12:30" },
{ StartTime: "05/21/2020 15:00", EndTime: "05/21/2020 15:30" },
{ StartTime: "05/21/2020 16:00", EndTime: "05/21/2020 16:30" },
{ StartTime: "05/21/2020 18:00", EndTime: "05/21/2020 18:30" },
{ StartTime: "05/21/2020 19:00", EndTime: "05/21/2020 19:30" },
{ StartTime: "05/21/2020 20:00", EndTime: "05/21/2020 20:30" },
{ StartTime: "05/21/2020 21:00", EndTime: "05/21/2020 21:30" }
]

and I want to group them using linq to create an object like below, the group by should be based on the time difference between the endtime of the first object and the starttime of the next object, as you can see in the object array, the first three object have 30 minutes difference between the endtime and starttime of their next object so it shows that they are related to each other, so I shoul take the first oject's start time and the endtime of the last object and create an object like this:

[
{ StartTime: "05/21/2020 10:00", EndTime: "05/21/2020 12:30" },
{ StartTime: "05/21/2020 15:00", EndTime: "05/21/2020 16:30" },
{ StartTime: "05/21/2020 18:00", EndTime: "05/21/2020 21:30" }
]

Upvotes: 1

Views: 197

Answers (1)

devcrp
devcrp

Reputation: 1348

If I understand you correctly, you need to merge those records that have a difference lower or equal to 30 minutes between the previous EndTime and current StartTime.

So assuming that your array is gonna be sorted, this is the simplest way I can think about:

public List<YourObject> MergeTimes(List<YourObject> list)
{
    List<YourObject> result = new List<YourObject>();
    result.Add(list.First());
    for (int i = 1; i < list.Count; i++)
    {
        if ((list[i].StartTime - list[i - 1].EndTime).TotalMinutes <= 30)
            result.Last().EndTime = list[i].EndTime;
        else
            result.Add(new { StartDate = list[i].StartTime, EndTime = list[i].EndTime });
    }

    return result;
}

Upvotes: 2

Related Questions