Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a better way to implement a Remove method for a Queue?
    text
    copied!<p>First of all, just grant that I do in fact want the functionality of a <code>Queue&lt;T&gt;</code> -- FIFO, generally only need <code>Enqueue</code>/<code>Dequeue</code>, etc. -- and so I'd prefer an answer other than "What you really want is a <code>List&lt;T&gt;</code>" (I know about <code>RemoveAt</code>).</p> <p>For example, say I have a <code>Queue&lt;DataPoint&gt; dataToProcess</code> 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:</p> <pre><code>while (dataToProcess.Count &gt; 0) { DataPoint pointToProcess = dataToProcess.Dequeue(); ProcessDataPoint(pointToProcess); } </code></pre> <p>But then suppose, for whatever reason, it's discovered that a particular data point which has been added to the queue should <em>not</em> be processed. Then it would be ideal if there were a method analogous to:</p> <pre><code>dataToProcess.Remove(badPoint); </code></pre> <p>I understand that there's really no feasible way to have a <code>Remove</code> method that does not involve some form of enumeration; however, since a <code>Queue&lt;T&gt;</code> doesn't really let you just walk in and remove some item randomly, the only solution I could figure out was this:</p> <pre><code>bool Remove(T item) { bool itemFound = false; // set up a temporary queue to take items out // one by one Queue&lt;T&gt; receivingQueue = new Queue&lt;T&gt;(); // move all non-matching items out into the // temporary queue while (this.Count &gt; 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 &gt; 0) { this.Enqueue(receivingQueue.Dequeue()); } return itemFound; } </code></pre> <p>Is this ridiculous? It certainly <em>looks</em> 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 <code>Remove</code> method would be to use a <code>LinkedList&lt;T&gt;</code> internally.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload