How to get alternate numbers using Enumerable.Range?

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

    What you are after here does not exist in the BCL as far as I'm aware of, so you have to create your own static class like this to achieve the required functionality:

    public static class MyEnumerable {
      public static IEnumerable AlternateRange(int start, int count) {
        for (int i = start; i < start + count; i += 2) {
          yield return i;
        }
      }
    }
    

    Then you can use it like this wherever you want to:

    foreach (int i in MyEnumerable.AlternateRange(0, 10)) {
      //your logic here
    }
    

    You can then also perform LINQ queries using this since it returns IEnumerable

    So if you want you can also write the above like this if you want to exclude the number 6

    foreach (int i in MyEnumerable.AlternateRange(0, 10).Where( j => j != 6)) {
      //your logic here
    }
    

    I hope this is what you are after.

    You can't have this as an extension method on the Enumerable class directly since that is a static class, and extension methods work on an object of a class, and not the class itself. That's why you have to create a new static class to hold this method if you want to mimic the Enumerable class.

提交回复
热议问题