Limit the size of a generic collection?

后端 未结 4 974
野的像风
野的像风 2020-12-31 18:20

Is there any way to limit the size of a generic collection?

I have a Stack of WriteableBitmap which I am using to store a clone of a WriteableBitmap on each change,

4条回答
  •  醉梦人生
    2020-12-31 18:53

    To elaborate on Tilak's answer here is some example code:

      public class LimitedSizeStack : LinkedList
      {
        private readonly int _maxSize;
        public LimitedSizeStack(int maxSize)
        {
          _maxSize = maxSize;
        }
    
        public void Push(T item)
        {
          this.AddFirst(item);
    
          if(this.Count > _maxSize)
            this.RemoveLast();
        }
    
        public T Pop()
        {
          var item = this.First.Value;
          this.RemoveFirst();
          return item;
        }
      }
    

提交回复
热议问题