2010-08-20 4 views
3

ASP.NET 3.5/C#의 목록을 사용하여 특정 달의 기존 목록 (약 20 개)을 필터링 할 수 있습니다. 따라서 사용자가 2010 년을 선택하면 (ddlFromYear.SelectedItem.Text == 2010) 반환 된 목록은 8 월까지만 이동하기 때문에 8 개월로 구성됩니다.리스트에서 달 목록 가져 오기 <DateTime>

내 질문은 - 내가 어떻게 int로, 심지어 선호 월별로 DateTime을 출력합니까? "팔월". 내가 다른 드롭 다운을 바인딩있을 때 그런 식으로 나는 모든 달 내가 년에 의해 결정된다 언급 한 바와 같이 (1 월, 2 월, 3 월 ...) (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

당신이 만약을 나열 할 수 있습니다 달의 이름으로 표현 된 날짜, 당신은 { "January", "February", "March" /* etc. */ };

+1

뚜렷한) 중복 달을 얻지 못하게하려면? – Martin

+0

@Martin, 절대적으로 중복이있을 수 있고 원하지 않는다면 .ToList() 전에 .Distinct()를 호출하십시오. 좋은 지적, 대답에 메모를 추가. –

+0

아니요 Distinct()가 필요하지 않습니다. 월이 이미 연도로 인해 필터링되어 다시 올 것입니다. – firedrawndagger

0

selected answer 원래 문제에 대한 좋은을 만들 것

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 년에 국한되지 않음)에서 실행해야하는 경우 다음과 같이 수행하는 것이 더 효율적이어야합니다.

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