Creating an array of sequential numbers
suggest changeLINQ provides a method that makes it easy to create a collection filled with sequential numbers. For example, you can declare an array which contains the integers between 1 and 100.
The Enumerable.Range
method allows us to create sequence of integer numbers from a specified start position and a number of elements.
The method takes two arguments: the starting value and the number of elements to generate.
Enumerable.Range(int start, int count)
Note that count
cannot be negative.
Usage:
int[] sequence = Enumerable.Range(1, 100).ToArray();
This will generate an array containing the numbers 1 through 100 ([1, 2, 3, ..., 98, 99, 100]
).
Because the Range
method returns an IEnumerable<int>
, we can use other LINQ methods on it:
int[] squares = Enumerable.Range(2, 10).Select(x => x * x).ToArray();
This will generate an array that contains 10 integer squares starting at 4
: [4, 9, 16, ..., 100, 121]
.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents