Monday, May 20, 2024
HomeProgrammingC# Tip: LINQ's Enumerable.Range to generate a range of consecutive numbers

C# Tip: LINQ’s Enumerable.Range to generate a range of consecutive numbers

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.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments

бнанс Створити акаунт on The Interview Process in Clark, Pampanga
Binance注册奖金 on Venus in Scorpio