Behavior after removing a list item from a <item> list in C #
I have a list List <Bitmap> memory = new List<Bitmap>();
. I use this list to save image states in a simple image program. I want to implement back and forth operations that will iterate between states stored in memory (= stored in list memory).
The memory will have a limited range, for example 20 states, which means that when I have 20 image modifications, and I make the 21st, I will delete the first state. Perhaps the operation memory.RemoveAt(0);
. What will happen to this list? I need a list with -1 elements than the previous one, and with shifted indices.
I have a list.Count = 20
list, I delete the first item, I want list.Count = 19
and the shifted indexes are something like trimmed free spaces, so index 1 of the original list will now have index 0 and index 2 of the original index will have an index of 1, etc. I found the TrimExcess
list TrimExcess
, it will do what I want, but I'm not sure.
When I have a list of 19, I can save the new state in last place on Add()
, so I will have a list of 20 again.
Do not confuse List
with array. The array has fixed positions and fixed size, but the list does not.
For arrays, there is no such thing as adding or removing elements. An array always has the length assigned when it was created.
The list is dynamic in its length. You add items, the list grows. You delete items, the list is compressed. If you add an item to the list, the item is always added to the list (you can call Insert
to insert at the specified position).
However, at any point in time, entries in the list will have indices ranging from 0 to Count-1
(“based on zero”). Even if you delete an item at position X in the middle of the list, there will be an item in that index (the one that was previously at position X + 1).
Summary. What you described in the “What I Need” paragraph is done automatically without any further action in your code.
About the TrimExcess
method: a list has Count
(the actual number of elements in the list) and Capacity
(the internal number of elements that a list can accept without changing its internal structures), Capacity
can be greater than Count
. This is because, from the inside, the list stores its elements in data structures that need to be reorganized when adding / removing.
To save time while adding, Capacity
grows in large steps. For example, when you add an item to the full list, 4 new “places” are initially created, so successive additions do not cause too much cost.
What TrimExcess
does is reorganize the internal data structures of the list so that Capacity
matches Count
. This takes longer than the more items in the list, so TrimExcess
should only be called when you are sure that you no longer need to add / remove any items.
In your case: Hands are disconnected from the TrimExcess
method.
Capacity
does not limit the list size! In C # there is no way to create a list that accepts a maximum of X items. You have to do it yourself.