Auto-Generating Sequences of Integer Values in C#

When we need to generate a sequence of integer values, we can do it manually using some kind of loop, or we make use of the Enumerable.Range method.

The following code illustrates:

var oneToTen = Enumerable.Range(1, 10);

int[] twentyToThirty = Enumerable.Range(20, 11).ToArray();

List<int> oneHundredToOneThirty = Enumerable.Range(100, 31).ToList();

We can also use the results of .Range and transform them in some way, for example to get the letters of the alphabet we could write something like this:

var alphabet = Enumerable.Range(0, 26).Select(i => Convert.ToChar('A' + i));

This will generate an IEnumerable<char> containing the letters A through Z.


(The .Range method is one of a smorgasbord of C# Tips and Traps that I cover in my Pluralisight C# courses.)

Add comment