Enumerable.Range - When does it make sense to use?

后端 未结 5 1104
-上瘾入骨i
-上瘾入骨i 2021-02-07 23:02

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?

5条回答
  •  没有蜡笔的小新
    2021-02-07 23:44

    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.

提交回复
热议问题