Is there an “upto” method in C#?

前端 未结 6 1784
攒了一身酷
攒了一身酷 2021-02-18 14:31

Here\'s a bit of code which prints out the squares of the numbers from 0 to 9:

for (int i = 0; i < 10; i++)
    Console.WriteLine(i*i);

Doin

6条回答
  •  星月不相逢
    2021-02-18 14:53

    Try Enumerable.Range, possibly in combination with Take or TakeWhile:

    IEnumerable values = Enumerable.Range(0, 20)
        .Take(10); // Not necessary in this example
    
    foreach(var value in values)
    {
        Console.WriteLine(value);
    }
    
    // or ...
    
    foreach(var i in Enumerable.Range(0, 10))
    {
        Console.WriteLine(i * i);
    }
    

    There is a ForEach on List that you could use to get closer syntax to what you want, but I consider it bad form. It takes a pure query/filter/transform syntax, that works in an effectively immutable fashion, and introduces side-effects.

    For your future amusement you might want to check out extension methods, IEnumerable, and yield return. A lot of generator-type functionality and interesting syntax becomes possible when you use those three things in combination. Although I would argue that this particular example isn't the best place to use them because the resulting syntax becomes a mess.

提交回复
热议问题