Is there a C# equivalent of Python's range with step
?
Documentation:
For a positive
step
, the contents of a ranger
are determined by the formular[i] = start + step*i
wherei >= 0
andr[i] < stop
.For a negative
step
, the contents of the range are still determined by the formular[i] = start + step*i
, but the constraints arei >= 0
andr[i] > stop
.
Example:
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
We can implement a static
utility class to handle this.
For completeness, this solution mimics Python's range
behavior for one parameter (stop
), two parameters (start
, stop
), and three parameters (start
, stop
, step
):
using System;
using System.Collections.Generic;
public static class EnumerableUtilities
{
public static IEnumerable<int> RangePython(int start, int stop, int step = 1)
{
if (step == 0)
throw new ArgumentException("Parameter step cannot equal zero.");
if (start < stop && step > 0)
{
for (var i = start; i < stop; i += step)
{
yield return i;
}
}
else if (start > stop && step < 0)
{
for (var i = start; i > stop; i += step)
{
yield return i;
}
}
}
public static IEnumerable<int> RangePython(int stop)
{
return RangePython(0, stop);
}
}
Example Usage with Step:
foreach (var i in EnumerableUtilities.RangePython(0, 10, 3))
{
Console.WriteLine(i);
}
Output:
0
3
6
9