I'm doing an appointment finder, where you can input multiple users' appoiments and it should find empty gaps in a list with multiple and variable DateRanges. The methods I wrote do unfortunately not work. How could I do this without a large library like TimePeriodLibrary.
List<DateRange> appointments = new List<DateRange>();
appointments.Add(new DateRange(new DateTime(2020, 7, 6, 10, 30, 0), new DateTime(2020, 7, 6, 11, 30, 0)));
appointments.Add(new DateRange(new DateTime(2020, 7, 7, 8, 30, 0), new DateTime(2020, 7, 7, 15, 30, 0)));
appointments.Add(new DateRange(new DateTime(2020, 7, 6, 16, 30, 0), new DateTime(2020, 7, 6, 17, 0, 0)));
var gaps = FindGapsInUsersCalendars(appointments, 60);
if (gaps.Any())
{
foreach (var gap in gaps)
{
Console.WriteLine($"{gap.Start} - {gap.End}");
}
}
private static List<DateRange> FindGapsInUsersCalendars(List<DateRange> appointments, int minutes)
{
List<DateRange> possibilities = new List<DateRange>();
foreach (var appointment in appointments)
{
if (!DateRangeIncludesDateForMinutes(appointment, appointment.End, minutes)) continue;
possibilities.Add(new DateRange(appointment.Start, appointment.Start.AddMinutes(minutes)));
}
return possibilities;
}
private static bool DateRangeIncludesDateForMinutes(DateRange dateRange, DateTime date, int minutes)
{
var tempDate = date;
for (var i = 0; i < minutes; i++)
{
if (!dateRange.Includes(tempDate.AddMinutes(1))) {
return false;
}
}
return true;
}
DateRange.cs class:
public class DateRange : IRange<DateTime>
{
public DateRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public bool Includes(DateTime value)
{
return (Start <= value) && (value <= End);
}
public bool Includes(IRange<DateTime> range)
{
return (Start <= range.Start) && (range.End <= End);
}
}
IRange.cs interface:
public interface IRange<T>
{
T Start { get; }
T End { get; }
bool Includes(T value);
bool Includes(IRange<T> range);
}