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.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading