The sometimes overlooked Enumerable.Range

I’ll start with confessing that the first time I saw LINQ and especially Enumerable.Range I didn’t see what I would use it for. Well, luckily times change…

An example

The other day when I was writing some code for a mockup and I hade to generate some fake data. More than often, that sort of code involves dealing with ranges in one way or another.

Let´s say we have a class, SomeObject, that has a property called Index which is an integer.
Now I wan´t to generate a range between 1 and 10 (i.e. 10 elements) of that class, SomeObject,  and put them in a collection and then printing out the indexer.

The for loop approach

image

So, what so bad about using a for loop then?
Well, nothing really if you’re into that “old” style programming but…

this is the output of that little program:

image

Hey, that’s not what I wanted!!
OK, well I can modify that for loop to print 1-10 if I’d make an effort but I still think my code is smelling since it is not showing its intent.

The Enumerable.Range approach

image

image

That’s more like it!!

Simply put…I want a range between 1 and 10…just give that to me.

The great thing about

Enumerable.Range is that it gives you an IEnumerable<int> and with that you have access to all those LINQ operators and such…much more than a for loop would give you.

Yet another example

Let’s say that had a dropdown list in asp.net and you would like to show a range of percentages from 5-100 with a 5 percent gap between them. Using the Enumerable.Range method that would give you:

from i in Enumerable.Range(1, 20)
let percentage = (i * 5)
select new ListItem
{
  Text = string.Format("{0}%", percentage),
  Value = percentage.ToString()
};

Databind that to a dropdown list and…

image

Now, isn’t that beautiful…??

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: