Dictionary of keys that match a date range

I would like to store data in a Generic Dictionary with keys that correspond to date ranges.

For example, I came up with the following idea

public class MyKey : IEquatable<MyKey> 
{
  public int Key { get; set; }
  public DateTime StartDate { get; set; }
  public DateTime EndDate { get; set; }

  public override int GetHashCode() 
  { 
    returns Key;
  }

  // if there is overlap in date range consider them equal
  public bool Equals(MyKey other)
  {
    if (Key!=other.Key)
      return false;
    else if(other.StartDate >=StartDate && other.StartDate <=EndDate) 
      return true;
    else if(other.EndDate >=StartDate && other.EndDate <=EndDate) 
      return true;
    else if(StartDate >=other.StartDate && StartDate <=other.EndDate) 
      return true;
    else if(EndDate >=other.StartDate && EndDate <=other.EndDate) 
      return true;
    else
      return false;
  }
}

Then I would use the dictionary as such

var dict = new Dictionary<MyKey,MyClass>();
Populate(dict);

// get an element where the current date is in the daterange of the key
// in the collection
var key = new MyKey();
key.Key=7;
key.StartDate=DateTime.Now;
key.EndDate=key.StartDate;

// retrieve the matching element for the date
var myclass = dict[key];

It was the best I could think of, but it seems like a trivial way to do it. I was thinking of adding a fourth property called the pick date. And would set this to null in entries in the dictionary, but would use it during a search in the Equals method.

I am wondering if anyone else came up with an elegant solution to this problem?

I should mention that first I will match the key, and then there may be date ranges for a particular key property.

+3
source share
2

getHashCode this.StartDate this.EndDate this.Key. . . , .

, int DateTime, , , . ( DateTimes , ) return myDictionary[myDictionary.Keys.Find(x=> value < x.EndDate && value > x.StartDate) && x.Key = key];

: return myDictionary[myDictionary.Keys.Find(x=> ((date1 < x.EndDate && date1 > x.StartDate)) || (date2 < x.EndDate && date2 > x.StartDate))) && x.Key = key];

, , .

return this.StartDate.Equals(o.StartDate) && this.EndDate.Equals(o.EndDate) && this.Key.Equals(o.Key);

, .

+1

Equals . , :

  • if x.Equals(y) && y.Equals(z) true, x.Equals(z) true.

- . .

. , , .

, , , , , . , , . , , .

+7

Source: https://habr.com/ru/post/1757397/


All Articles