Skip to content

Generate integer lists using LINQ

I was working on some old code which created three DropDown controls with hours, minutes and seconds.

This was the original code:

for (var i = 0; i < 24; i++)
    Hour.Items.Add(new ListItem(i.ToString()));
for (var i = 0; i < 60; i++)
    Minute.Items.Add(new ListItem(i.ToString()));
    Second.Items.Add(new ListItem(i.ToString()));

I wanted to "LINQify" this code using the LINQ range method:

Enumerable.Range(int start, int count)

This returns an IEnumerable<int> collection with the corresponding range of values. So, my DropDown controls are now created with the following code:

Hour.Items.AddRange(Enumerable.Range(0, 24).Select(i =>
                                               new ListItem(i.ToString())).ToArray());
Minute.Items.AddRange(Enumerable.Range(0, 60).Select(i =>
                                               new ListItem(i.ToString())).ToArray());
Second.Items.AddRange(Enumerable.Range(0, 60).Select(i =>
                                               new ListItem(i.ToString())).ToArray());

This could be optimized by using a variable for the sixty values which could be used twice.