首先,请承认我确实想要一个功能Queue<T>
-- 先进先出,一般只需要Enqueue
/Dequeue
等等——所以我更喜欢一个答案,而不是“你真正想要的是List<T>
“(我知道RemoveAt
).
例如,假设我有一个Queue<DataPoint> dataToProcess
需要按到达顺序处理的数据点。然后定期使用如下代码是有意义的:
while (dataToProcess.Count > 0) {
DataPoint pointToProcess = dataToProcess.Dequeue();
ProcessDataPoint(pointToProcess);
}
但是假设,无论出于何种原因,发现已添加到队列中的特定数据点应该not被处理。那么如果有一种类似于以下的方法那就更理想了:
dataToProcess.Remove(badPoint);
我知道确实没有可行的方法Remove
不涉及某种形式的枚举的方法;然而,自从一个Queue<T>
并不能真正让你走进去并随机删除一些物品,我能想到的唯一解决方案是:
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;
}
这很可笑吗?肯定是looks不好,但除了编写自定义类之外,我真的看不到更好的方法。即便如此,我能想到的最好的方法是实施Remove
方法是使用LinkedList<T>
内部。
我认为切换到内部具有 LinkedList 的新自定义类只需要几分钟,并且比现在的性能要高得多。
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; } }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)