【发布时间】:2010-07-30 18:08:28
【问题描述】:
我想用在日期范围内匹配的键将数据存储在通用字典中。
例如,我想出了以下想法
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;
}
}
那么我会像这样使用字典
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];
这是我能想到的最好的方法,但是这样做似乎很笨拙。我想添加第四个属性,称为选择日期。并且会在字典中的条目中将其设置为 null,但会在 Equals 方法中的查找期间使用它。
我想知道是否有其他人想出一个优雅的解决方案来解决这个问题?
我应该提到,我将首先匹配键,然后可能会有特定键属性的日期范围。
【问题讨论】:
-
非常类似于这个问题:stackoverflow.com/questions/2147505/…
-
你不想要一个字典。您需要一个区间树 (en.wikipedia.org/wiki/Interval_tree) 或区间跳过列表数据结构。
标签: c# collections dictionary