Limit the size of a generic collection?

JMK picture JMK · Dec 31, 2012 · Viewed 20.6k times · Source

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, meaning that I can undo easily by simply Popping the most recent WriteableBitmap off the stack.

The problem is the memory usage, I want to limit this stack to hold 10 objects, but I can't see a property allowing me to easily do this. Is there a way, or am I going to have to check the stack size on each change, and copy the last 10 objects into a new stack whenever I hit 10, and on each subsequent change? I know how to do this, but was hoping that there was an easier way, is there?

Answer

Oliver picture Oliver · Dec 10, 2013

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

  public class LimitedSizeStack<T> : LinkedList<T>
  {
    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;
    }
  }