MoreLINQ icon indicating copy to clipboard operation
MoreLINQ copied to clipboard

Add Range method with step

Open AlexRadch opened this issue 4 years ago • 2 comments

The Enumerable.Range does not have step parameter. Can you add Range method with step parameter, please. Range(int start, int count, int step)

It is different from Sequence(int start, int stop, int step) that Range will use count parameter instead stop boundary.

It will cover cases when you want get needed quantity of numbers with needed step between them.

It is like Sequence(start, start + step * (count - 1), step)

Also it will not generate infinite sequence if step is zero.

AlexRadch avatar Aug 24 '21 06:08 AlexRadch

        public static IEnumerable<int> Range(int start, int count, int step) {
            long max = ((long)start) + count - 1;
            if (count < 0 || max > Int32.MaxValue) throw Error.ArgumentOutOfRange("count");
            return RangeIterator(start, count, int step);
        }

        static IEnumerable<int> RangeIterator(int start, int count, int step) {
            var value = start;
            for (int i = 0; i < count; i++) 
            {
                yield return value;
                value += step;
            }
        }

AlexRadch avatar Aug 24 '21 06:08 AlexRadch

@AlexRadch FYI: this overload has been included in SuperLinq 4.0.0, which is now released.

viceroypenguin avatar Jul 20 '22 16:07 viceroypenguin

You can achieve this with MoreLINQ's Generate combined with LINQ's Take or roll it up into a simple extension method if you need to do this often:

static class Seq
{
    public static IEnumerable<int> Step(int start, int step, int count) =>
        MoreEnumerable.Generate(start, x => x + step).Take(count);
}

I am going to close this on the grounds that it's not adding anything new that cannot be achieved pretty trivially with a one-liner.

atifaziz avatar Oct 16 '22 14:10 atifaziz