c# - IEnumerable<T> 跳过无限序列

标签 c# linq fibonacci skip

我有一个使用 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/

相关文章:

c# - 将 IBuffer 转换为 IRandomAccessStream

c# - 如何每秒调用一个方法?

c# - Linq Where 比 SQL Where 快得多

c - 递归调用流程解释?

Haskell Fibonacci 似乎很慢

c# - 如何使用 C# 隐藏和显示 html 模板表?

C# 获取请求(API)-如何回调? (委托(delegate)?)

c# - 将 EF 原始 SQL 查询映射到特定属性?

c# - 使用 linq 返回对象列表,其中属性总和是列表列表中的 Max()

java - 斐波那契数列 long[] 数组在索引 92 后抛出负数