How to get alternate numbers using Enumerable.Range?

前端 未结 5 1362
梦谈多话
梦谈多话 2021-02-07 09:24

If Start=0 and Count=10 then how to get the alternate values using Enumerable.Range() the out put should be like { 0, 2, 4, 6, 8 }

5条回答
  •  故里飘歌
    2021-02-07 09:48

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

    public static MyExt
    {
      public static IEnumerable Range(int start, int end, Func 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.

提交回复
热议问题