I am looking to return a List or Dictionary Value, in order, but at a different index in the list or dictionary at different times.
For example, if I have the following Dictionary:
public static readonly Dictionary<int, int> DaysInTheMonth = new Dictionary<int, int>
{
{ 1, 31 }, // Jan
{ 2, 28 }, // Feb
{ 3, 31 }, // Mar
{ 4, 30 }, // Apr
{ 5, 31 }, // May
{ 6, 30 }, // Jun
{ 7, 31 }, // Jul
{ 8, 31 }, // Aug
{ 9, 30 }, // Sep
{ 10, 31 }, // Oct
{ 11, 30 }, // Nov
{ 12, 31 } // Dec
};
Where:
DaysInTheMonth[1]
Returns:
31
I may instead need to start at 7, and look all the way through to 5 again, in a Circular fashion.
for (int i = 7; i <= DaysInTheMonth.Count; i++)
{
Days += DaysInTheMonth[i];
}
Of course, I am missing the indexes 1 through 5 with this loop!
Using this ugly code:
private static int GetTotalDays(int startMonth, int endMonth)
{
int Days = 0;
int Index = startMonth;
bool Oneshot = (startMonth >= endMonth ? false : true);
for (int i = 1; i <= DaysInTheMonth.Count; i++)
{
Days += DaysInTheMonth[Index];
Index++;
if (Index >= DaysInTheMonth.Count)
{
Oneshot = true;
Index = 1;
}
if(Index > endMonth && Oneshot) break;
}
return Days;
}
There must be a better way!
I found this link that is similar: Looking for circular list solution however it does not allow for Indexing and changing as I require.
Instead of having a lot of if operators, moving Circular and an Indexer that is always needing to be checked.
There must be a better way!
EDIT: OnRequestForClarity.
The Gregorian Calendar is exactly 365.25 days, thus every 4 Years we have a Leap Year: 4 x 0.25 = 1 Day, so February becomes 29 Days for this Leap Year and back to 28 every other year! Every Month has a different number of Days, for example, 365.25 / 12 = 30.4375 days, however, not all months have this number of days! The number of Days is set in the Dictionary I provided above. Thus if one counts Days, as in a TimeSpan, this is fine if one is not looking at the months, but if one wants to count months, then one needs to Equate the correct Days to the Specific Months! Right? So Order of Counting is important!
Count from Month 1 to Month 3, do you get the same answer if you count from Month 6 to Month 8? No!
Order is Important!