Looking for structure that contains the benefits of a stack but the ability to only contain one item that matches a key.
For example Data comes in from various clients, I am only interested in the last piece of data from a particular client. So a dictionary would work very well. However I want to process the data from all the clients in a LIFO scenario, so a stack would be best.
Any ideas on combining the two?
There are several ways to interpret what you want. For instance when you
Push
a value with a key which already exists, what happens?If the LIFO aspect is the key consideration, you mainly need a modified
Stack
to associate a key with the data. ALinkedList
would be another alternative.Push
/Pop
on aList
would require implementing it asInsert(0)
andRemoveAt(0)
. This means the underlying array would be rebuilt for each and every operation. AStack
works inversely: new items are stored at the end of the array so it only has to be rebuilt periodically.Depending on the size and amount of data, that may not matter.
In mentioning
Dictionary
it becomes unclear if you also want access by key; that is, you canPop
items, but also retrieve them by key. That seems at odds with the nature of aStack
. First, a class to associate a Key (name) with an item:Then the stack-like collection. This will surely need work depending on the answers to the above and other unknowns. If the data size is small, I might stick with a
List
just for simplicity.The keys are case-insensitive. The base
Stack
provides the ordering, while theNameValuePair
provides the dictionary-like key.If you needed
Push
to treat dupes as new items (they loose their old place):Since
Stack
items are not meant to be removed by index, it becomes pretty expensive to do so (stack to list to array to reversed array to new stack). APopByKey
method is equally expensive. Hopefully, you wont need it. Ulta simple testing:It seems like you want something that would be called
HashStack<T>
.T
would need to implementIEquatable<T>
or overrideEquals
andGetHashCode
, or you can accept anIEqualityComparer<T>
.If you don't want to overcomplicate things, you'll need to implement
IList<T>
withPush
method. TheAdd
method will be called byPush
and it'll need to evaluate if the item to be added is already in the stack by either calling item'sGetHashCode
/Equals
or you can also maintain an internalHashSet<T>
to optimize this check that has already implemented equality check (HashSet<T>.Add
will returnfalse
if the item is already in the set...).Items would need to be also stored in an internal
List<T>
to being able to get last item by insertion order.