如何使用 Enumerable.Range 获取备用数字?
如果 Start=0
和 Count=10
那么如何使用 Enumerable.Range()
获取备用值 输出应类似于 { 0, 2, 4, 6, 8 }
并且如果 Start=1
且 Count=10
then { 1, 3, 5, 7, 9 }
可以得到连续值,
var a = Enumerable.Range(0,10).ToList();
但是如何得到替代值呢?
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 }
and if Start=1
and Count=10
then { 1, 3, 5, 7, 9 }
The continuous value can be get like
var a = Enumerable.Range(0,10).ToList();
but how to get the alternate values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将 Range 应生成的项目数减半(其第二个参数),然后将结果值加倍,将给出正确的项目数并确保增量为 2。
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.
代码中的
count
参数看起来像是循环的结束
点。用法:
MyExt.Range(1, 10, x => x + 2)
通过步骤 2 返回 1 到 10 之间的数字MyExt.Range(2, 1000, x => x * 2)
返回 2 到 1000 之间的数字,每次乘以 2。The
count
parameter in your code looks like anend
point of the loop.Usage:
MyExt.Range(1, 10, x => x + 2)
returns numbers between 1 to 10 with step 2MyExt.Range(2, 1000, x => x * 2)
returns numbers between 2 to 1000 with multiply 2 each time.据我所知,您在这里所追求的内容并不存在于 BCL 中,因此您必须像这样创建自己的静态类来实现所需的功能:
想要的地方使用它:
然后您可以在任何您 然后还可以使用它执行 LINQ 查询,因为它返回 IEnumerable
因此,如果您想要排除数字 6,您也可以像这样编写上面的内容,
我希望这就是您想要的。
您不能直接将其作为
Enumerable
类的扩展方法,因为它是一个静态类,并且扩展方法适用于类的对象,而不是类本身。这就是为什么如果您想模仿Enumerable
类,您必须创建一个新的静态类来保存此方法。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:
Then you can use it like this wherever you want to:
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
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 theEnumerable
class.使用 Linq 并指定最小值、长度和步长值可以更简单地完成此操作:
使用 0 到 10,步长为 2:
输出:
使用 1 到 10,步长为 2:
输出:
您可以更进一步,制作一个简单的函数来使用最小值、最大值和步长值来输出它:
将范围长度设置为
max - min + 1
的原因是为了确保max
代码>值包含在内。如果max
应该是独占的,请删除+ 1
。用法:
This can be done more simply using Linq and by specifying the minimum, length, and step values:
Usage with 0 through 10 at a step size of 2:
Output:
Usage with 1 through 10 at a step size of 2:
Output:
You could go further and make a simple function to output it using a minimum, maximum, and step value:
The reason to set the range length to
max - min + 1
is to ensure themax
value is inclusive. If themax
should be exclusive, remove the+ 1
.Usage: