Quickly create a list of integers

by Charles Cherry

To quickly create a list of integers to use in an Asp.Net MVC view , use the Enumerable.Range function.

The following example creates a list of integers from 1 to 20, then converts the list to something that can be used in an HTML dropdown list:

var list = Enumerable.Range(1, 20).ToList();
var myOptions = list
    .ConvertAll(x => new SelectListItem
       Text = x.ToString(), Value = x.ToString()

To use the list:

@Html.DropDownListFor(m => m.SomeIntProperty, myOptions)

Which generates the following HTML:

<select id="SomeIntProperty" name="SomeIntProperty">
  <option selected="selected" value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
  <option value="11">11</option>
  <option value="12">12</option>
  <option value="13">13</option>
  <option value="14">14</option>
  <option value="15">15</option>
  <option value="16">16</option>
  <option value="17">17</option>
  <option value="18">18</option>
  <option value="19">19</option>
  <option value="20">20</option>