Using LINQ queries instead of “for” loops

LINQ can easily replace for each loops, but when it comes to replacing old-style for loops, it’s a bit trickier – what exactly are you enumerating over? Nothing but a fictional set of integers.

Luckily the System.Linq.Enumerable namespace comes with a handy static method for just such these occasions. Consider the following code: –

var list = new List <int> ();
for (int i = 0; i < 10; i++)
    list.Add (i * i);


You can actually easily rewrite this as a LINQ query like so: –

var list = from i in System.Linq.Enumerable.Range (0, 9)
           select i * i;


The Range () method generates an IEnumerable <int> collection of sequential numbers as per the parameters passed in from which you can select data over.

I think it’s very nice 🙂

Leave a Reply

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

You are commenting using your 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