Search code examples
c#pythonrangexrange

Is there an equivalent of Pythons range(12) in C#?


This crops up every now and then for me: I have some C# code badly wanting the range() function available in Python.

I am aware of using

for (int i = 0; i < 12; i++)
{
   // add code here
}

But this brakes down in functional usages, as when I want to do a Linq Sum() instead of writing the above loop.

Is there any builtin? I guess I could always just roll my own with a yield or such, but this would be so handy to just have.


Solution

  • You're looking for the Enumerable.Range method:

    var mySequence = Enumerable.Range(0, 12);