C# Expand Dictionary or Hashtable to include Pop and Push (LIFO)

前端 未结 2 855
灰色年华
灰色年华 2021-01-24 09:07

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,

2条回答
  •  滥情空心
    2021-01-24 09:51

    It seems like you want something that would be called HashStack.

    T would need to implement IEquatable or override Equals and GetHashCode, or you can accept an IEqualityComparer.

    If you don't want to overcomplicate things, you'll need to implement IList with Push method. The Add method will be called by Push and it'll need to evaluate if the item to be added is already in the stack by either calling item's GetHashCode/Equals or you can also maintain an internal HashSet to optimize this check that has already implemented equality check (HashSet.Add will return false if the item is already in the set...).

    Items would need to be also stored in an internal List to being able to get last item by insertion order.

提交回复
热议问题