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++) { range.Add(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));
or
List<int> range = Enumerable.Range(0, 10)).ToList();
Remark
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.