firedrawndagger
firedrawndagger

Reputation: 3733

Get list of months from List<DateTime>

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();
    }

Upvotes: 3

Views: 7086

Answers (2)

hangy
hangy

Reputation: 10859

The selected answer is good for the original problem. For anyone who may come to this question and needs to run this over a larger number of dates (ie. not limited to a year), it should be more efficient to do it like this:

DateTimeFormatInfo formatInfo = CultureInfo.CurrentCulture.DateTimeFormat;
List<string> month = dates.Select(n => n.Month)
                          .Distinct()
                          .OrderBy(n => n)
                          .Select(n => formatInfo.GetMonthName(n))
                          .ToList();

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126854

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. */ };

Upvotes: 7

Related Questions