2013-01-23 71 views
-1

我對此表示年月性能視圖模型:如何重構此屬性的代碼? C#

public IEnumerable<SelectListItem> Years 
    { 
     get 
     { 
      return new SelectList(
       Enumerable.Range(1900, 112) 
       .OrderByDescending(year => year) 
       .Select(year => new SelectListItem 
       { 
        Value = year.ToString(CultureInfo.InvariantCulture), 
        Text = year.ToString(CultureInfo.InvariantCulture) 
       } 
      ), "Value", "Text"); 
     } 
    } 

    public IEnumerable<SelectListItem> Months 
    { 
     get 
     { 
      return new SelectList(
       Enumerable.Range(1, 12) 
       .OrderByDescending(month => month) 
       .Select(month => new SelectListItem 
       { 
        Value = month.ToString(CultureInfo.InvariantCulture), 
        Text = month < 10 ? string.Format("0{0}", month) : month.ToString(CultureInfo.InvariantCulture) 
       } 
      ), "Value", "Text"); 
     } 
    } 

當然我在這裏使用複製粘貼&辦法)我如何重構這個代碼? Mabby以某種方式將數字作爲參數傳遞給一些輔助方法?

+5

您可能對http://codereview.stackexchange.com更好的運氣/ – cadrell0

回答

1

只是大聲思索,但這裏的常見部分是「獲取一系列值,排序它們,並將每個值都包含在文本值爲(如何獲取文本)的包裝對象中」。這說明,你可能做這樣的事情:

private IEnumerable<SelectListItem> GetXXXX(
     int start, 
     int count, 
     Func<int,string> nameGetter) 
{ 
    return Enumerable 
     .Range(start, count) 
     .OrderByDescending (i => i) 
     .Select(i => 
      new SelectListItem() 
      { 
       Value = i.ToString(CultureInfo.InvariantCulture), 
       Text = nameGetter(i) 
      }); 
} 

那麼你的「月」,例如,將是:

public IEnumerable<SelectListItem> Months 
{ 
    get 
    { 
     return GetXXXX(1, 12, m => 
       m < 10 
       ? string.Format("0{0}", m) 
       : m.ToString(CultureInfo.InvariantCulture)); 
    } 
}