C# 中是否有返回IEnumerator
无限整数序列的函数[0, 1, 2, 3, 4, 5 ...]
?
我目前在做
Enumerable.Range (0, 1000000000).Select (x => x * x).TakeWhile (x => (x <= limit))
枚举所有正方形直到limit
. 我意识到这是有效的,但如果有一个从 开始计数的内置函数0
,我更愿意使用它。
你可以自己滚。
IEnumerable<BigInteger> Infinite() {
BigInteger value = 0;
while (true) {
yield return value++;
}
}
编辑
你为什么不把限制传递给Range
?这个可能差一...
Enumerable.Range(0, limit).Select(x => x * x);
我对这个编辑错了。
这发生在我身上,并且适合我正在做的事情:
Enumerable.Range (0, int.MaxValue)
正如评论者指出并在此答案中说明的那样,该int
类型具有最大和最小界限,因此您实际上不能将其用作无限序列的值类型。但是,您可以做出如下妥协:
int
类型BigInteger
- 就像在这个答案中所做的那样。int
类型。既然前者已经讲过了,那我就讲讲后者。下面是我用来提供int
值枚举的类,如果该枚举超出范围(过高或过低),它将引发异常。我已经对上/下边缘情况进行了单元测试,一切似乎都很好。
internal class SequentialIntProviderImpl : ISequentialIntProvider
{
public int Start { get; }
public int Step { get; }
private int _current;
public SequentialIntProviderImpl(int start, int step)
{
Start = start;
Step = step;
_current = start;
}
public int Next()
{
AssertNextIsInBounds();
_current += Step;
return _current;
}
private void AssertNextIsInBounds()
{
AssertNextLeqIntMax();
AssertNextGeqIntMin();
}
private void AssertNextGeqIntMin()
{
if (Step < 0)
{
int MinAllowableCurrent = int.MinValue - Step;
if (_current < MinAllowableCurrent)
{
throw new IndexOutOfRangeException($"Current index {_current} plus step {Step} will exceed int Min value");
}
}
}
private void AssertNextLeqIntMax()
{
if(Step > 0)
{
int maxAllowableCurrent = int.MaxValue - Step;
if(_current > maxAllowableCurrent)
{
throw new IndexOutOfRangeException($"Current index {_current} plus step {Step} will exceed int Max value");
}
}
}
}
/// <summary>
/// Provides iteration over an arithmetic sequence of ints, starting at the given value & increasing by the given step
/// </summary>
public interface ISequentialIntProvider
{
/// <summary>
/// Value to start at
/// </summary>
int Start { get; }
/// <summary>
/// Value by which to increase the sequence at each successive term
/// </summary>
int Step { get; }
/// <returns>The next successive term in the sequence</returns>
int Next();
}