C#C
C#2y ago
Jake

Does anyone have any suggestions to potentially improve and make this function work better?

I have a function that basically is supposed to look for gaps for a specified duration on a desired day. I'm looking for ways to improve this and I'm also open for suggestions if there's a completely better way to do this. Even if its some magical linq query.

List<TimeRange> FindAvailableGaps(List<TimeRange> existingBookings, DateTime desiredDate, TimeSpan desiredDuration)
{
    // Define the full day range
    var fullDayRange = new TimeRange(desiredDate, desiredDate.AddDays(1));

    // Get the gaps between existing bookings
    var bookedPeriods = existingBookings.OrderBy(b => b.Start).ToList();
    var availableGaps = new List<TimeRange>();

    if (bookedPeriods.Count > 0 && bookedPeriods[0].Start > fullDayRange.Start)
    {
        availableGaps.Add(new TimeRange(fullDayRange.Start, bookedPeriods[0].Start));
    }

    for (int i = 0; i < bookedPeriods.Count - 1; i++)
    {
        var gap = new TimeRange(bookedPeriods[i].End, bookedPeriods[i + 1].Start);
        if (gap.Duration >= desiredDuration)
        {
            availableGaps.Add(gap);
        }
    }

    if (bookedPeriods.Count > 0 && bookedPeriods.Last().End < fullDayRange.End)
    {
        availableGaps.Add(new TimeRange(bookedPeriods.Last().End, fullDayRange.End));
    }

    return availableGaps;
}


I call the code using this and then also sort it by how close it is to the specified time that I am looking for.

// Find available gaps
var availableGaps = FindAvailableGaps(existingBookings, desiredDate, desiredDuration);

availableGaps = availableGaps.OrderBy(gap => Math.Abs(((decimal)(gap.Start.TimeOfDay.TotalMinutes + gap.End.TimeOfDay.TotalMinutes) / 2) -(decimal)desiredTime.TotalMinutes)).ToList();


I know for a fact there is probably a better way to do this and im open for suggestions. Thanks 🙂

I am using the TimePeriodLibrary.NET currently.
Was this page helpful?