tags:

views:

73

answers:

3

I have a for loop that check whether some checkboxes are checked

foreach (CheckBox chk in this.Controls.OfType<CheckBox>())
{
    if (chk.Checked)
    {
        //Some code here
    }
}

There are 12 checkboxes, 1 for each month.

What i want is to calculate the number of days between a variable StartDate and the last month. It's hard to explain sorry.

For example, StartDate = 1st September 2010, Checked Boxes are April, October and December.

The result should be the days between 01/09/2010 and 01/04/2011.

If StartDate = 1st November 2010 then the result would be the days between 01/11/2010 and 01/10/2011.

I'm think I struggling because the loop goes from jan to dec. If it was started from the startdate month I'd be OK.

Please ask some questions if i need to explain more.

A: 
int num=0,currentyear=2010;
for(i=startmonth;i<endmonth;i++)
{
if(i=13)
{
i=1;
currentyear++
}
num+=datetime.daysinmonth(currentyear,i);
}

i think that it will work for you

eden
I know how to calculate the difference between the months. The problem is working out which is the endmonth.
Ash Burlaczenko
+1  A: 

Assuming you are olny interested in the DateTime logic, this should do:

private static TimeSpan GetLatestSpan(IEnumerable<int> monthNumbers, DateTime startDate)
{
  var candidateDates = monthNumbers
                    .Select(month => GetNearestDateInDifferentMonthWithSameDay(startDate, month));

  return candidateDates.Max() - startDate;
}

private static DateTime GetNearestDateInDifferentMonthWithSameDay(DateTime startDate, int month)
{
 return new DateTime(month > startDate.Month ? startDate.Year : startDate.Year + 1, month, startDate.Day);
}

Using your example,

var checkedMonthNumbers = new List<int>();

foreach (CheckBox chk in this.Controls.OfType<CheckBox>())
       {
         if (chk.Checked)
                {
                    checkedMonthNumbers.Add(GetMonthNumberFromCheckBox(chk));
                }
       }

MessageBox.Show("Required timespan is " + GetLatestSpan(checkedMonthNumbers, StartDate));

EDIT:

Note that I would probably rewrite the loop as:

var checkedMonthNumbers = Controls.OfType<CheckBox>()
                                  .Where(chk => ck.Checked)
                                  .Select(chk => GetMonthNumberFromCheckBox(chk));
Ani
A: 
  • Search the selected months for the nearest preceding month to startDate. So basically just search only preceding months.

  • If there is none, pick the last month from the list.

khai_khai