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:
1 2 3 4 5 6 |
IEnumerable<int> numbers = Enumerable.Range(1, 10); foreach (int num in numbers) { Console.WriteLine(num); } |
If we runt this code it prints the 10 numbers from 1 to 10:
1 2 3 4 5 6 7 8 9 10 |
1 2 3 4 5 6 7 8 9 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):
1 2 3 4 5 6 |
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x); foreach (int num in squares) { Console.WriteLine(num); } |
This time we get the squares back instead of the number 1 to 10:
1 2 3 4 5 6 7 8 9 10 |
1 4 9 16 25 36 49 64 81 100 |
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.