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 🙂