Home > Back-end >  How do I ensure that my datetime period overlaps an existing period?
How do I ensure that my datetime period overlaps an existing period?

Time:12-04

I have this

Dictionary<(DateTime from, DateTime to), HashSet<string>> uniquelyChangedPeriods = new();

in which I store unique string from a given time period

so ex.

between (from: 2020-01-01T00:00:00Z, to:2022-01-01T00:00:00Z) I could store string such as {"Hi","Adress", "Something"} Lets say I then want to add a change registered in (2020-01-01T00:00:00Z, 2021-01-01T00:00:00Z) {"Hi","Adress", "Something2"}

but since (2020-01-01T00:00:00Z,2021-01-01T00:00:00Z) is included in (from: 2020-01-01T00:00:00Z , to:2022-01-01T00:00:00Z), I want to include the "Something2" in the entry (from: 2020-01-01T00:00:00Z , to:2022-01-01T00:00:00Z) and not create a seperate entry in the dictionary for this... how do easily do this overlap checking, and ensure it is included in the overlapping timeframe?

CodePudding user response:

Here is one way you could go about this:

Dictionary<(DateTime from, DateTime to), HashSet<string>> uniquelyChangedPeriods = new();

var ((from, to), addData) = ((new DateTime(2020, 1, 1), new DateTime(2021, 1, 1)), new[]{ "test" });

var existing = uniquelyChangedPeriods.FirstOrDefault(x => x.Key.from <= from && x.Key.to >= to);
if (existing.Value != null)
{
    foreach (var a in addData) existing.Value.Add(a);
}
else
{
    var set = new HashSet<string>();
    foreach (var a in addData) set.Add(a);
    uniquelyChangedPeriods.Add((from, to), set);
}

However, you might want to reconsider your design and approach here. Using a dictionary in this way will work, but may prove difficult to maintain down the line.

Edit:

For example, the current approach does not account for a potential case where the new period completely or partially overlaps the existing one and spans beyond the boundaries of that existing one. To better deal with this case, you might want to create a class holding the data, which has start and end as properties; then, you can change start and end of entries (ie. expand them) as you please. A List<> could hold the existing entries.

  • Related