I have a view model with properties that represent years and months:
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");
}
}
Definitely I use copy & paste approach here) How can I refactor this code? Mabby somehow passing the numbers as parameters to some helper method?
Just thinking out loud, but the common part here is “Get a range of values, order them, and wrap each in a wrapper object with a text value of (how to get text)”. That stated, you could possibly do something like:
Then your “Months”, for example, would be: