Know your .NET Framework Episode 2 : getting a range of integers

If you need a list of integers filled with all numbers in a specific range, you will often do this :

List<int> range = new List<int>();
for (int i = rangeStart; i < RangeEnd; i++)

or you will write a method

public IEnumerable<int> GetRange(int start, int end)
  for (int i = start; i < end; i++)
    yield return i;

and call it:

List<int> range = GetRange(0, 10).ToList();

Good news : this method already exists in the framework !

You can find it in the System.Linq namespace : it’s the Enumerable.Range static method, and it’s available since framework 3.5.

This method returns an IEnumerable<int>, you can use it like this, or convert it to an array or a list.
to use it :
List<int> range = new List<int>(Enumerable.Range(0, 10));
List<int> range = Enumerable.Range(0, 10)).ToList();


Note that the first parameter is the start, but the second is not the end ! it’s a count !, so if you want to use it by specifying a start and an end you will have to do this :

int start = 5;
int end = 50;
List<int> range = Enumerable.Range(start, (end-start)+1)).ToList();

It’s handy to reduce the code size when you want to fill a dropdown or other things that requires a range of integers.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>