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

Daren Thomas picture Daren Thomas · Aug 13, 2009 · Viewed 18.3k times · Source

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.

Answer

LukeH picture LukeH · Aug 13, 2009

You're looking for the Enumerable.Range method:

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