我有一个使用 BigInteger 的斐波那契数列的简单实现:
internal class FibonacciEnumerator : IEnumerator<BigInteger>
{
private BigInteger _previous = 1;
private BigInteger _current = 0;
public void Dispose(){}
public bool MoveNext() {return true;}
public void Reset()
{
_previous = 1;
_current = 0;
}
public BigInteger Current
{
get
{
var temp = _current;
_current += _previous;
_previous = temp;
return _current;
}
}
object IEnumerator.Current { get { return Current; }
}
}
internal class FibonacciSequence : IEnumerable<BigInteger>
{
private readonly FibonacciEnumerator _f = new FibonacciEnumerator();
public IEnumerator<BigInteger> GetEnumerator(){return _f;}
IEnumerator IEnumerable.GetEnumerator(){return GetEnumerator();}
}
这是一个 无限 序列,因为 MoveNext()
总是返回 true。
调用时使用
var fs = new FibonacciSequence();
fs.Take(10).ToList().ForEach(_ => Console.WriteLine(_));
输出符合预期(1,1,2,3,5,8,...)
我想选择 10 个项目,但从第 100 个位置开始。我试着通过
调用它fs.Skip(100).Take(10).ToList().ForEach(_ => Console.WriteLine(_));
但这不起作用,因为它从头开始输出十个元素(即输出又是 1,1,2,3,5,8,...)。
我可以通过调用 SkipWhile 跳过它
fs.SkipWhile((b,index) => index < 100).Take(10).ToList().ForEach(_ => Console.WriteLine(_));
从第 100 个元素开始正确输出 10 个元素。
是否需要/可以在枚举器中实现其他东西以使 Skip(...)
工作?
最佳答案
Skip(n)
不访问 Current
,它只是调用 MoveNext()
n
次。
所以需要在MoveNext()
中进行自增,即the logical place for that operation anyway :
Current does not move the position of the enumerator, and consecutive calls to Current return the same object until either MoveNext or Reset is called.
关于c# - IEnumerable<T> 跳过无限序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32398006/