Limit the size of the total collection?

Is there a way to limit the size of the total collection?

I have a Stack of WriteableBitmap that I use to store a clone of writeableBitmap every time I change, which means that I can easily undo by simply popping the latest WriteableBitmap from the stack.

The problem is memory usage, I want to limit this stack to 10 objects, but I don’t see a property that allows me to easily do this. Is there a way, or will I have to check the size of the stack every time I change and copy the last 10 objects to a new stack whenever I press 10, and every subsequent change? I know how to do this, but was hoping there was an easier way, is there?

+2
source share
4 answers

To do this, you need to implement your own shell. There is no direct choice.

class FixedSizeStack : Stack { private int MaxNumber; public FixedSizeStack(int Limit) : base() { MaxNumber = Limit; } public override void Push(object obj) { if (this.Count < MaxNumber) base.Push(obj); } } 
+6
source

To clarify Tilak's answer, here is a sample 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; } } 
+17
source

You can use LinkedList , which is a double list of links to simulate a circular stack .

You can AddFirst() match Push() . If Count is 10, you can use RemoveLast() .

For Pop() you can use RemoveFirst()

+3
source

You will need to check the size (you will get an exception, which I consider if you set a limit, and do not check its completeness).

Edit

You will not get an exception if the size has been set, but the size just increases, so you need to check the size (via http://msdn.microsoft.com/en-us/library/6335ax0f.aspx ): -

If the graph is already equal to capacity, the stack capacity is increased by automatically redistributing the internal array and existing elements are copied to the new array to the new element.

+1
source

All Articles