How To Create a Sequence of Numbers in C#

For some problems you need a sequence of numbers. In Python I would use the range() function, while in C# the method Enumerable.Range() gives us what we need. We must specify the starting point and how many numbers we want:

If we runt this code it prints the 10 numbers from 1 to 10:

To be precise, Enumerable.Range() gives an IEnumerable<int> back. This allows us to directly use the enumeration and do some operations on them (like calculating their squares):

This time we get the squares back instead of the number 1 to 10:

Enumerable.Range() is easy to overlook. Before you create a loop to get the numbers you may go for a more direct approach and use the Range() function instead.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.