Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the size of a generic collection?

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?

like image 814
JMK Avatar asked Dec 31 '12 11:12

JMK


People also ask

What is the limit of list in C#?

2147483647 because all functions off List are using int.

What is capacity in list?

Capacity is the number of the elements which the List can store before resizing of List needed. But Count is the number of the elements which are actually present in the List.

What is t in Stack T?

Type Parameters T. Specifies the type of elements in the stack. Inheritance. Object. Stack<T>

What is initial capacity of a list C#?

The capacity property in ArrayList class gets or sets the number of elements that the ArrayList can contain. The default capacity is 4. If 5 elements are there, then its capacity is doubled and would be 8.


2 Answers

You can use LinkedList which represents doubly link list to simulate Circular Stack.

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

For Pop() you can use RemoveFirst()

like image 142
Tilak Avatar answered Sep 29 '22 15:09

Tilak


You have to implement your own wrapper to achieve that. There is no direct option available.

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);
    }

}
like image 33
Habib Avatar answered Sep 29 '22 13:09

Habib