Is there a better way to implement a Remove method for a Queue?
.net, c#, queue
Solution
I think switching over to a new custom class that had a LinkedList internally would only take you a few minutes and would be much more performant than what you have now.
public class SpecialQueue<T>
{
LinkedList<T> list = new LinkedList<T>();
public void Enqueue(T t)
{
list.AddLast(t);
}
public T Dequeue()
{
var result = list.First.Value;
list.RemoveFirst();
return result;
}
public T Peek()
{
return list.First.Value;
}
public bool Remove(T t)
{
return list.Remove(t);
}
public int Count { get { return list.Count; } }
}
Problem
First of all, just grant that I do in fact want the functionality of a `Queue<T>` -- FIFO, generally only need `Enqueue`/`Dequeue`, etc. -- and so I'd prefer an answer other than "What you really want is a `List<T>`" (I know about `RemoveAt`). For example, say I have a `Queue<DataPoint> dataToProcess` of data points that need to be processed in the order in which they arrived. Then periodically it would make sense to have some code like this: ``` while (dataToProcess.Count > 0) { DataPoint pointToProcess = dataToProcess.Dequeue(); ProcessDataPoint(pointToProcess); } ``` But then suppose, for whatever reason, it's discovered that a particular data point which has been added to the queue should not be processed. Then it would be ideal if there were a method analogous to: ``` dataToProcess.Remove(badPoint); ``` I understand that there's really no feasible way to have a `Remove` method that does not involve some form of enumeration; however, since a `Queue<T>` doesn't really let you just walk in and remove some item randomly, the only solution I could figure out was this: ``` bool Remove(T item) { bool itemFound = false; // set up a temporary queue to take items out // one by one Queue<T> receivingQueue = new Queue<T>(); // move all non-matching items out into the // temporary queue while (this.Count > 0) { T next = this.Dequeue(); if (next.Equals(item)) { itemFound = true; } else { receivingQueue.Enqueue(next); } } // return the items back into the original // queue while (receivingQueue.Count > 0) { this.Enqueue(receivingQueue.Dequeue()); } return itemFound; } ``` Is this ridiculous? It certainly looks bad, but I can't really see a better way, other than writing a custom class. And even then, the best way I could think to implement a `Remove` method would be to use a `LinkedList<T>` internally.