[英]IEnumerable<T> Skip on unlimited sequence
我有一個使用 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(...)
工作的東西?
CodeCaster 的答案是正確的 - 我只想指出,您實際上並不需要為這樣的事情實現自己的可枚舉:
public IEnumerable<BigInteger> FibonacciSequence()
{
var previous = BigInteger.One;
var current = BigInteger.Zero;
while (true)
{
yield return current;
var temp = current;
current += previous;
previous = temp;
}
}
編譯器將為您創建枚舉器和可枚舉項。 對於像這樣的簡單可枚舉,差異並不是那么大(您只是避免了大量樣板),但是如果您確實需要比簡單的遞歸函數更復雜的東西,它會產生巨大的差異。
將您的邏輯移至MoveNext
:
public bool MoveNext()
{
var temp = _current;
_current += _previous;
_previous = temp;
return true;
}
public void Reset()
{
_previous = 1;
_current = 0;
}
public BigInteger Current
{
get
{
return _current;
}
}
Skip(10) 只是調用MoveNext
10 次,然后調用Current
。 在MoveNext
中而不是在當前中完成操作也更合乎邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.