I am having the following class
public class MyDictionary : SortedList<int, MyData>
{
}
At the moment the Key
in the SortedList
represents a year number, e.g. 2014, 2015, 2016 etc. The Value
represents the data for the year.
Now I have a new requirement saying that having a Value
per year is not enough and this class should support a finer granularity.
The new granularity looks like this:
- Yearly
- Quarterly
- Monthly
- Weekly
- Daily
Of course one instance of MyDictionary
should represent one time frame, e.g. SortedList<Yearly, MyData>
, SortedList<Monthly, MyData>
.
The data that goes into MyDictionary
spans over several years. That means that I cannot use, e.g. the number of a month in a monthly granularity. Example:
2014-12
2015-01
2015-02
...
2015-12
As you can see the number 12 is twice in the list.
My problem is, that I don't know what data type to use for the Key
and how to access the Values
in MyDictionary
to meet the new requirement.
Any ideas?
Modification from 24.02.2016:
I must add a little more information to the original question.
- The granularity is known at runtime only
- The access to the
Values
via thearray indexer []
must be runtime optimised. It will be called millions of times in a very short period of time. - The class that uses
MyDictionary
uses aDateTime
object to access theValues
. Example:
public class ClientClass
{
public void AccessMyDictionary(DateTime date)
{
MyData data = MyDictionary[date.Year];
// Do something with data
}
}
It looks to me that the most obvious thing to do is to have DateTime
as an indexer data type. Then create an indexer in the MyDictionary
class to take care of granularity. Example:
public enum Period
{
Yearly,
Quarterly,
Monthly,
Weekly,
Daily
}
public class MyDictionary
{
private Period period;
private SortedList<DateTime, MyData> sortedList;
public MyDictionary(Period period)
{
this.period = period;
sortedList = new SortedList<DateTime, MyData>();
}
public MyData this[DateTime i]
{
get
{
// Implement here an algorithm for granularity, similar to the one of Tomas Lycken in the 1st answer
}
set
{
// Implement here an algorithm for granularity, similar to the one of Tomas Lycken in the 1st answer
}
}
}
What do you think? Is that runtime optimised?
Many thanks Konstantin