How to get alternate numbers using Enumerable.Range?

前端 未结 5 1267
梦谈多话
梦谈多话 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:45

    This can be done more simply using Linq and by specifying the minimum, length, and step values:

    Enumerable.Range(min, length).Where(i => (i - min) % step == 0);
    

    Usage with 0 through 10 at a step size of 2:

    var result = Enumerable.Range(0, 10).Where(i => (i - 10) % 2 == 0);
    

    Output:

    0, 2, 4, 6, 8
    

    Usage with 1 through 10 at a step size of 2:

    var result = Enumerable.Range(1, 10).Where(i => (i - 10) % 2 == 0);
    

    Output:

    1, 3, 5, 7, 9
    

    You could go further and make a simple function to output it using a minimum, maximum, and step value:

    public static IEnumerable RangedEnumeration(int min, int max, int step)
    {
        return Enumerable.Range(min, max - min + 1).Where(i => (i - min) % step == 0);
    }
    

    The reason to set the range length to max - min + 1 is to ensure the max value is inclusive. If the max should be exclusive, remove the + 1.

    Usage:

    var Result = RangedEnumeration(0, 10, 2); // 0, 2, 4, 6, 8, 10
    var Result = RangedEnumeration(1, 10, 2); // 1, 3, 5, 7, 9
    var Result = RangedEnumeration(1000, 1500, 150); // 1000, 1150, 1300, 1450
    

提交回复
热议问题