This is a mirror of official site: http://jasper-net.blogspot.com/

C#/.NET Little Wonders: The Enumerable.Range() Static Method

| Monday, April 30, 2012
Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Thanks for all of your patience while I’ve been dealing with other matters these last few weeks.  I didn’t want to let my post slide a third week, so I decided to say a few words about a small static method in the Enumerable class from System.Linq. 

Using Range() to generates a sequence of consecutive integers

So, if we look in the Enumerable static class, where most of the linq extension methods are defined, we will also see a static method called Range() whose purpose is to generate a range of integers from a given start value and for a given count. 

It’s syntax looks like:

Range(int start, int count)

Returns a sequence of int from start to (start + count – 1).
So, for example, the code snippet below will create an List<int> of the numbers from 1 to 10:

 var numbers = Enumerable.Range(1, 10).ToList();

So, this seems simple enough, right? Well, yes, it is a handy way to create a sequence of consecutive int values that you can use directly, but when coupled with other constructs, it has many other uses as well.

Using Range() to feed a more complex LINQ expression

For example, if we wanted a list of the first 5 even numbers, we could start with the number of expected items and multiply up by our step factor in a Select():

     // take sequence 0, 1, 2, 3, 4 and multiply each by two...
     var evens = Enumerable.Range(0, 5).Select(n => n*2).ToList();

Or, you could create a range over the total range of values and use Where() to filter it down:

    // generates sequence from 0..9, but only selects even ones
    var odds = Enumerable.Range(0, 10).Where(n => (n % 2) == 0).ToList();

But the great thing about Range() is you don’t have to use it to just produce numbers, you can use the sequence it generates either directly or as the starting point for a more complex LINQ expression. 

For example, if we wanted to generate a series of strings for font sizes we want to allow in a windows form, we could do that easily:

// takes the range from 1 to 10 and multiples by 10 and puts % on end.
var percentages = Enumerable
   .Range(1, 10)
   .Select(i => (i * 10) + " pt")
   .ToArray();

This would give us an array of strings containing “10 pt”, “20 pt”, “30 pt”, … “100 pt”.

Read more: James Michael Hare
QR: Inline image 2

Posted via email from Jasper-net

0 comments: