When programming it\'s almost instinctive deciding when to use a for loop, or foreach, but what is the determining factors or problem space for choosing to use Enumerable.Range?
As mentioned, Enumerable.Range isn't directed at looping, but rather creating the range. This makes one liners in Linq possible without the need of creating subsets.
One additional advantage of that power is, you could even generate a subrange within a sub statement, something that is not always possible with a for
and lambda's, because yield is not possible inside lambdas.
For example, a SelectMany
could also use an Enumerable.Range.
Test collection:
class House
{
public string Name { get; set; }
public int Rooms;
}
var houses = new List
{
new House{Name = "Condo", Rooms = 3},
new House{Name = "Villa", Rooms = 10}
};
The example on itself doesn't hold much value of course, but for getting all the rooms, the implementation in Linq would be:
var roomsLinq = houses.SelectMany(h => Enumerable.Range(1, h.Rooms).Select(i => h.Name + ", room " + i));
With iteration, it would require 2 iterations:
var roomsIterate = new List();
foreach (var h in houses)
{
for (int i = 1; i < h.Rooms + 1; i++)
{
roomsIterate.Add(h.Name + ", room " + i);
}
}
You could still say, the 2nd code is more readable, but that boils down to using Linq or not in general.
So, one step further, we want a IEnumerable
of all the rooms (a string enumerable of rooms per house).
Linq:
listrooms = houses.Select(h => Enumerable.Range(1, h.Rooms).Select(i => h.Name + ", room " + i));
But now, we would need 2 collections when using iteration:
var list = new List>();
foreach (var h in houses)
{
var rooms = new List();
for (int i = 1; i < h.Rooms + 1; i++)
{
rooms.Add(h.Name + ", room " + i);
}
list.Add(rooms);
}
Another scenario, imo one of the great things about Linqs and lambdas, is that you can use them as parameters (e.g. for injections purposes), which is made possible in an easier way with Enumerable.Range.
For example, you have a function, that takes a parameter roomgenerator
static IEnumerable CreateFurniture(Func> roomgenerator){
//some house fetching code on which the roomgenerator is used, but only the first 4 rooms are used, so not the entire collection is used.
}
The rooms iteration above could be returned with Enumerable.Range, but with iteration either a sub collection for rooms must be created first, or a separate function that yields the results. The subcollection would have the great disadvantage that it is always populated completely, even if only one item is needed from the enumeration. The separate method is often overkill, since it is only needed for a single parameter use, hence Enumerable.Range can save the day.