How to get alternate numbers using Enumerable.Range?

Enumerable.Range(0, 10).Where(i => i % 2 == 0); // { 0, 2, 4, 6, 8 }
Enumerable.Range(0, 10).Where(i => i % 2 != 0); // { 1, 3, 5, 7, 9 }

The count parameter in your code looks like an end point of the loop.

public static MyExt
{
  public static IEnumerable<int> Range(int start, int end, Func<int, int> step)
  {
    //check parameters
    while (start <= end)
    {
        yield return start;
        start = step(start);
    }
  }
}

Usage: MyExt.Range(1, 10, x => x + 2) returns numbers between 1 to 10 with step 2 MyExt.Range(2, 1000, x => x * 2) returns numbers between 2 to 1000 with multiply 2 each time.


Halving the number of items that Range should generate (its second parameter) and then doubling the resulting values will give both the correct number of items and ensure an increment of 2.

Enumerable.Range(0,5).Select(x => x * 2)