views:

66

answers:

1

I'm using a List in ASP.NET 3.5/C# to filter an existing list of dates (about 20 in total) on a specific month. So if a user selects a year of 2010 (ddlFromYear.SelectedItem.Text == 2010) then the returned list would consist of only 8 months because we only go up to August.

My question is - how do I output the DateTime as an int, or even preferrably a Month, e.g. "August". That way when I'm binding another DropDown I can list out all the months (January, February...) which as I mentioned would be determined by years (2009, 2010...)

    int yearSelected;
    bool success = Int32.TryParse(ddlFromYear.SelectedItem.Text, out yearSelected);
    if (success)
    {
        List<DateTime> datesSelected = new List<DateTime>();
        datesSelected =
            (from n in dates
             where n.Year.Equals(yearSelected)
             select n).ToList();

        dateMonths.Sort();
        ddlFromMonth.Items.Clear();
        ddlFromMonth.DataSource = datesSelected;
        ddlFromMonth.DataBind();
    }
+5  A: 

If you want the dates expressed as the month name, you would do something like

List<string> months = (from n in dates 
                      where n.Year.Equals(yearSelected)
                      select n.ToString("MMM")).ToList();

// optionally include call to .Distinct() prior to .ToList() if there 
// could be duplicates and you want to exclude them

Which would create { "January", "February", "March" /* etc. */ };

Anthony Pegram
Add a Distinct() to that to not get duplicate months?
Martin
@Martin, absolutely, if there could be duplicates and you do not want them, call .Distinct() before .ToList(). Good point, adding note to answer.
Anthony Pegram
No I wouldn't need Distinct() as the months would already come back filtered due to year.
firedrawndagger