I have list List <Bitmap> memory = new List<Bitmap>();. I use this list for saving states of image in simple program for working with images. I want to implement operations back and forward, which will iterate between states saved in memory (= saved in list memory).
Memory will have only a limited range, for example 20 states, which means when I will have 20 modifications of an image and I do the 21st, I will delete the first state. Probably by operation memory.RemoveAt(0);. What will happen with the list then? I need the list with -1 items than the previous list and with shifted indexes.
I have list list.Count = 20, I delete the first item, I want list.Count = 19 and shifted indexes – something like trim free spaces so index 1 of original list will have now index 0 and index 2 of original index will have index 1, etc.. I found a method of list TrimExcess, it would do what I want but I’m not sure.
When I will have list of 19 I can save the new state to the last place by Add(), so I will have again the list of 20.
Do not confuse a
Listwith an array. An array has fixed positions and a fixed size, while a list does not.For arrays, there’s not such thing as “adding” or “removing” items. An array always has the length it was assigned when creating it.
A list is dynamic in its length. You add items, the list grows. You remove items, the list shrinks. If you add an item to a list, the item is always appended to the list (you can call
Insertto insert at a specified position).However, at any given time, the entries in a list will have indices starting at 0 ranging to
Count-1(“zero based”). Even if you remove an item at position X “in the middle of the list”, there will be an item at 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 actions in your code.
About the
TrimExcessmethod: A list has aCount(the actual number of elements in the list) and aCapacity(the internal number of elements the list can take without having to resize its internal structures). TheCapacitycan be greater than theCount. This is, because internally the list stores its items in data structures that need to be reorganized when adding/removing.To save time when adding, the
Capacitygrows in larger steps. For example, when you add an item to a list that is full, internally 4 new “places” are created, so that consecutive adds don’t cause too much overhead.What
TrimExcessdoes is to reorganize the list’s internal data structures so that theCapacitymatches theCount. This takes the more time the more items are in the list, soTrimExcessshould only be called when you’re sure that you’ll not need to add/remove any elements anymore.In your case: Hands off the
TrimExcessmethod.Capacitydoes not limit the list’s size! In C#, there’s no option to create a list that takes a maximum of X elements. You’ll have to do that yourself.