C# equivalent of Python's range with step?
c#, ienumerable, python, range
Solution
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
Problem
Is there a C# equivalent of Python's range with `step`? Documentation: For a positive `step`, the contents of a range `r` are determined by the formula `r[i] = start + step*i` where `i >= 0` and `r[i] < stop`. For a negative `step`, the contents of the range are still determined by the formula `r[i] = start + step*i`, but the constraints are `i >= 0` and `r[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] ```