Bohn
Bohn

Reputation: 26919

Determining Date Overlapping in a list of dates

I have a list of items that each have a start and end date time component.

var myDates= new List<Tuple<DateTime, DateTime>>();

Which I fill it out with some date.

Now I wanted to loop through them and see if any two of those have any overlapping date rang. So I did this:

var myOverlapList = (from start in myDates
                   from endDate in myDates
                   where !Equals(start, end)
                   where start.Item1 <= end.Item2 && start.Item2 >= end.Item1
                   select end);

It works when dates have overlap for example one day back and forth between two dates BUT it does NOT work when two date entries have the EXACT SAME values.
So how I can fix my code or just something else to achieve that.

Upvotes: 0

Views: 1025

Answers (1)

The

where !Equals(startDate, endDate)

line, which is supposed to filter out the same date tuple actually is filtering out any duplicate, so any matching timespan falls out of the selection. So your query will return all DateTime tuples, which overlap with some other tuple in the collection, but only unique. And you want also to return tuples if they encounter in your collection more then once.Your problem, actually is that you can not differentiate between two different items with the same value. So you need a discriminator for them and because you use a list, the index of an item fits well. You can cast your Tuple<DateTime, DateTime> collection into, e. g. {int id, Tuple<DateTime, DateTime> range} object by

var datesWithId = dates.Select((d, i) => new {id = i, range = d});

and then modify your query like this:

var anyOverlap = (from startDate in datesWithId
                  from endDate in datesWithId
                  where startDate.id!=endDate.id
                  && startDate.range.Item1 <= endDate.range.Item2
                  && startDate.range.Item2 >= endDate.range.Item1
                  select endDate.range).Distinct();

Upvotes: 2

Related Questions