2010-08-20 49 views
3

我在ASP.NET 3.5/C#中使用列表来筛选特定月份中的现有日期列表(总计约20个)。因此,如果用户选择2010年(ddlFromYear.SelectedItem.Text == 2010),那么返回的列表将只包含8个月,因为我们只能到8月份。从列表中获取月份列表<DateTime>

我的问题是 - 如何输出DateTime作为整数,甚至最好是一个月,例如“八月”。这样,当我绑定另一个下拉我可以列出所有的月份(一月,二月...),这正如我所提到会通过几年来决定(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(); 
    } 

回答

6

如果您想表示月份名称的日期,你会做这样的事情

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 

这将创建{ "January", "February", "March" /* etc. */ };

+1

添加一个独特的( )以免重复月份? – Martin 2010-08-20 18:37:31

+0

@Martin,如果可能存在重复而你不想要它们,那么在.ToList()之前调用.Distinct()。好点,补充说明回答。 – 2010-08-20 18:38:18

+0

不,我不需要Distinct(),因为月份会因年份而过滤回来。 – firedrawndagger 2010-08-20 18:43:10

0

selected answer有利于原始问题。对于任何人谁可以来这个问题,需要在日期(即不限于一年),较大数量的运行它,它应该是更有效地做到这一点是这样的:

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