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 numbers = new List();
for (int i = 4; i < 7; i++)
numbers.Add(i);
IEnumerable squares = numbers.Select(x => x * x);
// or building the result directly
List 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.