When you need to generate a series of numbers in ascending order, you can simply use a while
loop with an enumerator, or you can use Enumerable.Range
.
This method, which you can find in the System.Linq
namespace, you can generate an array of numbers by passing two parameters: the get started number and the total numbers add.
Enumerable.Range(start:10, count:4) // [10, 11, 12, 13]
⚠ Note that the second parameter is not the last number of the series. Rather, it is the length of the returned collection.
Obviously it also works if the start
parameter is negative:
Enumerable.Range(start:-6, count:3) // [-6, -5, -4]
But it won’t work if the count
parameter is negative: in fact it will be a ArgumentOutOfRangeException
:
Enumerable.Range(start:1, count:-23) // Throws ArgumentOutOfRangeException
// with message "Specified argument was out of the range of valid values"(Parameter 'count')
⚠ Beware of overflows: it’s not a circular array, so if you use the int.MaxValue
value as you build the collection you will get another ArgumentOutOfRangeException
.
Enumerable.Range(start:Int32.MaxValue, count:2) // Throws ArgumentOutOfRangeException
💡 Smart tip: you can use it Enumerable.Range
to generate collections of other types! Just use LINQs Select
method in combination with Enumerable.Range
:
Enumerable.Range(start:0, count:5)
.Select(_ => "hey!"); // ["hey!", "hey!", "hey!", "hey!", "hey!"]
Note that this pattern is not very efficient: you must first build a collection of N integers and then generate a collection of N strings. If you care about performance, go for a simple one while
loop – if you need a quick and dirty solution, this other approach works fine.
To block
In this C# tip, we learned how to generate sets of numbers using LINQ.
This is an incredibly useful LINQ method, but you have to remember that the second parameter does not specify the last value of the collection, but rather the length of the collection itself.
C# Tip: DO NOT use nameof to value constants
Programming in C# involves making numerous decisions to ensure code efficiency and maintainability. One common aspect is dealing with constants,…
Can we run a Java program without the main method
Can we run a Java program without the main method? The mainly method is executed when we execute a class in…
Java program to calculate students grades in 2 different ways
Java program to calculate students grades: In this post we will learn different ways to calculate the figure from a student…
Java String charAt method explanation with examples
Java String charAt method: The signAt method of Java string is used to find a character at a given index. This…
3 Ways to Convert System.nanoTime to Seconds in Java
How to convert System.nanoTime to seconds in Java: In this post we will learn how to convert System.nanoTime Unpleasant seconds in…
4 different Java programs to find the HCF or GCD of two numbers
Java programs to find the HCF or GCD of two numbers: Let’s learn how to find the HCF of two numbers…