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;
}
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);
var key = new MyKey();
key.Key=7;
key.StartDate=DateTime.Now;
key.EndDate=key.StartDate;
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.
source
share