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?
Your example is already good enough.
I could do the same code with a for loop building the result
There are basically two ways of how you could build it using loops:
// building a collection for the numbers first
List<int> numbers = new List();
for (int i = 4; i < 7; i++)
numbers.Add(i);
IEnumerable<int> squares = numbers.Select(x => x * x);
// or building the result directly
List<int> squares = new List();
for (int i = 4; i < 7; i++)
numbers.Add(i * i);
The thing with both solutions is that you actually need to create a collection which you add to. So you have a collection of numbers somewhere.
But look at the Enumerable.Range
solution: Enumerable.Range is a generator, it returns an IEnumerable
just like all other Linq methods and only creates the things when they are iterated. So there never exists a collection with all the numbers.
foreach is about iterating over an existing set/collection.
Enumerable.Range is for generating a set/collection. You wouldn't, generally, want to write a for loop just to generate a set if it can be generated by Enumerable.Range - you'd just be writing boilerplate code that's longer and requires you to allocate some kind of storage (e.g. a List<int>) to populate first.
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<House>
{
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<string>();
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<IEnumerable<string>>
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<IEnumerable<string>>();
foreach (var h in houses)
{
var rooms = new List<string>();
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<Furniture> CreateFurniture(Func<House,IEnumerable<string>> 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.
You can think about Enumerable.Range
like a tool of retriveing subset of a collection.
If content of collection are value types, you create also a new instance of every of them.
Yes, you can do it with for
loop, by setting correctly bounds of iteration, but thinking such way, almost all LINQ
can be implemented in other ways (at the end it's just a library).
But it have short, concise and clear syntax, that's why it's used so widely.
Enumerable.Range()
is a generator, i.e. it is a simple and powerfull way to generate n
items of some sort.
Need a collection with random number of instances of some class? No problem:
Enumerable.Range(1,_random.Next())
.Select(_ => new SomeClass
{
// Properties
});