views:

67

answers:

1

I'm looking for an INotifyCollectionChanged implementation of Stack and Queue. I could roll my own but I don't want to reinvent the wheel.

+3  A: 

With Stacks and Queues (almost by definition) you only have access to the top of the stack or head of the queue. It's what differentiates them from a List. (and so, that's why you haven't found one)

To answer though you could write your own, I would do it by deriving from ObservableCollection, then in the case of a stack implementing the Push as an Insert at offset 0 (and pop as returning index 0 then RemoveAt index 0); or with a queue you could just Add to the end of the list to Enqueue, and the grab and remove the first item, as with the stack, for Dequeue. The Insert, Add and RemoveAt operations would be called on the underlying ObservableCollection and so cause the CollectionChanged event to be fired.


You might also be saying that you simply want to bind or be notified when the one item you are supposed to have access to changes. You would create your own class again, derived from Stack or Queue, and fire the CollectionChanged event manually when:

  • Something is pushed onto or popped from a stack
  • Something is dequeued from a queue
  • Something is queued on the queue, when the queue was previously empty
Kieren Johnstone
I recommend the first approach for `ObservableStack` - derive from (or better, contain) an `ObservableCollection`. The second approach would be better for `ObservableQueue` - derive from `Queue` and implement your own notifications. This is because any `ObservableQueue` built on a `List` will have O(N) performance for either `Enqueue` or `Dequeue`, whereas everything else will be O(1). This would have a performance impact if there are a lot of elements in the queue.
Stephen Cleary
I decided to make a generic observable class that simply implement INotifyCollectionChanged. Classes call internal Stack and Queue methods and raise the appropriate event. Favoring composition over inheritance as Stack and Queue methods aren't virtual (which I'm having trouble understanding why).
Goran