tags:

views:

523

answers:

3

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.

Ok, using the advice given below, the sum of the first n squares can be written like this:

Enumerable.Range(1, n).Sum(i => i*i);
+15  A: 

You're looking for the Enumerable.Range method:

var mySequence = Enumerable.Range(0, 12);
LukeH
Note: this requires System.Linq and C# 3.0.
crb
+3  A: 
Enumerable.Range(start, numElements);

Sample here.

Mark Rushakoff
+2  A: 

Enumerable.Range(0,12);

Mel Gerats