如何使用Enumerable.Range获取替代数字? [英] How to get alternate numbers using Enumerable.Range?

查看:88
本文介绍了如何使用Enumerable.Range获取替代数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果Start=0Count=10,那么如何使用Enumerable.Range()获取备用值 输出应该像{ 0, 2, 4, 6, 8 }

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 }

,如果Start=1Count=10,则{ 1, 3, 5, 7, 9 }

连续值可以像

var a = Enumerable.Range(0,10).ToList();

但是如何获取替代值?

推荐答案

据我所知,BCL中不存在您所追求的东西,因此您必须像这样创建自己的静态类才能实现所需的功能:

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<int> 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
}

然后您还可以使用它执行LINQ查询,因为它返回IEnumerable

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

因此,如果您要排除数字6,也可以像上面这样写

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.

您不能直接将其用作Enumerable类的扩展方法,因为它是静态类,并且扩展方法适用于类的对象,而不适用于类本身.因此,如果要模仿Enumerable类,则必须创建一个新的静态类来容纳此方法.

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.

这篇关于如何使用Enumerable.Range获取替代数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆