Date:

Share:

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

Related Articles

When you need to create a sequence of numbers in ascending order, you can simply use a while A loop with a counter, or you can use Enumerable.Range.

This method, which you can find in System.Linq namespace, allows you to create a sequence of numbers by passing two parameters: e start number and the Total numbers add.

Enumerable.Range(start:10, count:4) 

⚠ Note that the second parameter is No The last number of the sequence. Instead, it’s the length of the returned collection.

Of course it works even if start The negative parameter:

Enumerable.Range(start:-6, count:3) 

But it won’t work if count The parameter is negative: in fact, it will throw an ArgumentOutOfRangeException:

Enumerable.Range(start:1, count:-23) 

⚠ Beware of flooding: it is not a circular array, so if you cross the int.MaxValue value while building the collection you will get another ArgumentOutOfRangeException.

Enumerable.Range(start:Int32.MaxValue, count:2) 

💡 Smart tip: You can use Enumerable.Range Create other types of collections! Just use LINQ’s Select Method in conjunction with Enumerable.Range:

Enumerable.Range(start:0, count:5)
    .Select(_ => "hey!"); 

Note that this template is not very efficient: You must first build a collection with N integers to create a collection of N strings. If you care about performance, go with simple while Loop – If you need a quick and dirty solution, this other approach works great.

Additional readings

There are many ways to achieve a similar result: another interesting one is by using yield return Disclaimer:

🔗 C# Tip: Use return return to return one item at a time | Code4IT

This article first appeared on Code4IT 🐧

finishing

In this C# tip, we learned how to create collections of numbers using LINQ.

This is an incredibly useful LINQ method, but you must remember that the second parameter does not specify the last value of the collection, but the length of the collection itself.

I hope you enjoyed this article! Let’s keep in touch Twitter or on LinkedIn, If you want! 🤜🤛

Happy coding!

🐧

.

Source

Popular Articles