加强型无穷集合:InfiniteList<T>,可指定遍历方向和偏移量,只要集合有元素并且偏移量不为 0,将永远遍历下去。...

 主类:

    public class InfiniteList<T> : IEnumerable<T> {
        public List<T> SourceList { get; }
        int start { get; }
        public int Step { get; set; } = 1;

        public InfiniteList(IEnumerable<T> source) : this(0, source) {
        }

        public InfiniteList(int start, IEnumerable<T> source) {
            this.start = Math.Max(Math.Min(start, source.Count()), -1);
            SourceList = new List<T>(source);
        }

        public InfiniteEnumerator<T> GetInfiniteEnumerator() {
            return new InfiniteEnumerator<T>(this, start);
        }

        public IEnumerator<T> GetEnumerator() {
            return GetInfiniteEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }

 迭代类:

    public class InfiniteEnumerator<T> : IEnumerator<T> {
        InfiniteList<T> list;
        int start;

        public int Index { get; set; }
        public int Step { get; set; }
        public InfiniteEnumerator(InfiniteList<T> source, int start) {
            list = source;
            Index = start - source.Step;
            this.start = start;
            Step = source.Step;
        }

        public T Current {
            get { return list.SourceList[Index]; }
        }

        object IEnumerator.Current {
            get { return Current; }
        }

        public void Dispose() {
        }

        public bool MoveNext() {
            if (list.SourceList.Count == 0) {
                return false;
            }
            if (Step == 0) {
                return false;
            }
            Index += Step;
            while (Index > list.SourceList.Count - 1) {
                Index -= list.SourceList.Count;
            }
            while (Index < 0) {
                Index += list.SourceList.Count;
            }

            return true;
        }

        public void Reset() {
            Index = start;
        }
    }

 

转载于:https://www.cnblogs.com/ly45/p/5515863.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值