从List<DateTime>获取月份列表

3
我正在使用ASP.NET 3.5/C#中的List来过滤一个包含大约20个日期的现有列表,以特定月份为基准进行过滤。因此,如果用户选择2010年(ddlFromYear.SelectedItem.Text == 2010),则返回的列表仅包含8个月,因为我们只到八月份。
我的问题是 - 如何将DateTime输出为int,或者更好地说,作为月份,例如“August”。这样,当我绑定另一个DropDown时,我可以列出所有的月份(January,February...),这些月份如我所提到的将由年份(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();
    }
2个回答

7
如果您希望日期以月份名称表示,您可以这样做:
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

这将创建一个{ "一月", "二月", "三月" /* 等等 */ }的数组;


1
在此添加Distinct()以避免重复的月份? - Martin
@Martin,完全正确,如果可能存在重复项而您不想要它们,请在 .ToList() 之前调用 .Distinct()。好的建议,我会在答案中添加注释。 - Anthony Pegram
不需要使用Distinct(),因为由于年份的筛选,月份已经被过滤了。 - firedrawndagger

0

所选答案对于原始问题是不错的。对于任何需要在更多日期上运行(即不仅限于一年)的人来说,这样做应该更有效:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接