2010-08-20 50 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();