Note that there are some explanatory texts on larger screens.

plurals
  1. PODictionary Keys that match over a Date Range
    primarykey
    data
    text
    <p>I would like to store data in Generic Dictionary with keys that match over Date Ranges.</p> <p>For instance, I came up with the following idea</p> <pre><code>public class MyKey : IEquatable&lt;MyKey&gt; { 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 &gt;=StartDate &amp;&amp; other.StartDate &lt;=EndDate) return true; else if(other.EndDate &gt;=StartDate &amp;&amp; other.EndDate &lt;=EndDate) return true; else if(StartDate &gt;=other.StartDate &amp;&amp; StartDate &lt;=other.EndDate) return true; else if(EndDate &gt;=other.StartDate &amp;&amp; EndDate &lt;=other.EndDate) return true; else return false; } } </code></pre> <p>Then the I would use a Dictionary as so</p> <pre><code>var dict = new Dictionary&lt;MyKey,MyClass&gt;(); 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]; </code></pre> <p>This was the best I could come up with, however it seems kludgy way to do this. I thought of adding a fourth property called selection date. And would set that to null in the entries in the dictionary but would use it during lookups in the Equals method.</p> <p>I am wondering if anyone else has come up with an elegant solution to this problem?</p> <p>I should mention that I will be matching on the key first and then there could be date ranges for the specific key property.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload