Maximum capacity collection in c#

前端 未结 9 2004
Happy的楠姐
Happy的楠姐 2020-12-09 04:27

In the .Net BCL is there a collection data structure similar to list that has a maximum capacity, say configured to 100 items, which when item 101 is added the original firs

相关标签:
9条回答
  • 2020-12-09 05:25

    There's not one available, but it should be easy to write a function to accomplish this with an array or collection.

    0 讨论(0)
  • 2020-12-09 05:26

    A really simple rolling window

    public class RollingWindow<T> : IEnumerable<T>
    {
        private readonly T[] data;
        private int head;
        private int nextInsert = 0;
    
        public RollingWindow(int size)
        {
            if (size < 1)
                throw new Exception();
            this.data = new T[size];
            this.head = -size;
        }
    
        public void Add(T t)
        {
            data[nextInsert] = t;
            nextInsert = (nextInsert + 1) % data.Length;
            if (head < 0)
                head++;   
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            if (head < 0)
            {
                for (int i = 0; i < nextInsert; i++)
                    yield return data[i];
            }
            else
            {
                for(int i = 0; i < data.Length; i++)
                    yield return data[(nextInsert + i) % data.Length];
            }
        }
    
        System.Collections.IEnumerator 
            System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 05:27

    ArrayList.FixedSize() method.

    0 讨论(0)
提交回复
热议问题