Jef*_*eff 3 c# collections dictionary
我想将数据存储在通用字典中,其中的键与日期范围匹配.
例如,我提出了以下想法
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我将使用字典
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];
Run Code Online (Sandbox Code Playgroud)
这是我能想到的最好的东西,但这似乎很难实现.我想添加一个名为选择日期的第四个属性.并且会在字典中的条目中将其设置为null,但会在Equals方法的查找期间使用它.
我想知道是否还有其他人想出这个问题的优雅解决方案?
我应该提一下,我将首先匹配键,然后可能有特定键属性的日期范围.
您对Equals的实施违反了覆盖Equals的指导原则.特别是您的实现不满足传递性规则:
- 如果
x.Equals(y) && y.Equals(z)返回true,则x.Equals(z)返回true.
打破这个准则是一个坏主意,可能会导致问题和混乱.我建议你不要这样做.
我会避免将间隔作为密钥存储在字典中.如果您愿意,可以将特定键的间隔列表作为值添加到字典中,但它不应该是键的一部分.
当您搜索查找间隔时,可以先使用字典键获取该键的间隔列表,然后迭代间隔以找到与您的参数重叠的间隔.如果特定键的间隔不重叠,则可以对它们进行排序并使用二进制搜索来查找特定间隔.如果特定键的间隔可以重叠,您可以查看其他数据结构,例如间隔树.
相关问题