tags:

views:

2446

answers:

4

I would like to use the generic queue class as described in the .NET framework (3.5) but I will need a Remove(int index) method to remove items from the queue. Can I achieve this functionality with an extension method? Anyone care to point me in the right direction?

+1  A: 

Someone will probably develop a better solution, but from what I see you will need to return a new Queue object in your Remove method. You'll want to check if the index is out of bounds and I may have got the ordering of the items being added wrong, but here's a quick and dirty example that could be made into an extension quite easily.

public class MyQueue<T> : Queue<T> {
    public MyQueue() 
        : base() {
        // Default constructor
    }

    public MyQueue(Int32 capacity)
        : base(capacity) {
        // Default constructor
    }

    /// <summary>
    /// Removes the item at the specified index and returns a new Queue
    /// </summary>
    public MyQueue<T> RemoveAt(Int32 index) {
        MyQueue<T> retVal = new MyQueue<T>(Count - 1);

        for (Int32 i = 0; i < this.Count - 1; i++) {
            if (i != index) {
                retVal.Enqueue(this.ElementAt(i));
            }
        }

        return retVal;
    }
}
David Anderson
Thanks David,That looks interesting, but surely there is quite some overhead for creating a new queue like this everytime?Perhaps I am better off solving the inverse problem: just use a list and making my own Queue,Peek and Dequeue methods?
Alex
I wrote a blog on this a few minutes ago that should answer any questions about the code I posted.http://renevo.com/blogs/developer/archive/2009/02/10/a-bad-approach-to-adding-removeat-to-a-queue-t.aspx
David Anderson
Your for loop does not seem correct. I don't see a reason for not iterating through all the queue items. The correct is for (Int32 i = 0; i < this.Count; i++)
Felipe Lima
+6  A: 

What you want is a List<T> where you always call RemoveAt(0) when you want to get the item from the Queue. Everything else is the same, really (calling Add would add an item to the end of the Queue).

casperOne
+2  A: 

In fact, this defeats the whole purpose of Queue and the class you'll eventually come up with the will violate the FIFO semantics altogether.

Anton Gogolev
Yep, and that goes for any specialized collection. (Stack, Queue, other). If it doesn't do what you want, its not the right collection to use.
David Anderson
A: 

David Anderson's solution is probably the best but has some overhead. Are you using custom objects in the queue? if so, add a boolean like cancel

Check with your workers that process the queue if that boolean is set and then skip it.

PoweRoy