我需要在第 n 个元素处重新排队,其中 n 由有序键定义。
ConcurrentQueue<KeyValuePair<string, SomeClass>> queue = new ConcurrentQueue<KeyValuePair<string, SomeClass>>();
queue.RequeueByOrderedKey(key, element)
或者
queue.RequeueN(index, element)
...因为看起来有必要自己实现这个,我正在考虑基于公共的东西
class Class1 : KeyedCollection<K,V>{}
it'd be nice to have Class1 : OrderedKeyedCollection<K,V>{}
这是我做的一些代码。我会把它放在这里以供评论,然后可能会移动它作为答案。可能还没有正确处理并发问题。
public class QueueExt<TK, TV> : SortedList<TK, TV> {
#region Constructors
public QueueExt(Func<TV, TK> getKey = null) {
GetKey = getKey;
}
private Func<TV, TK> GetKey = null;
public QueueExt(int capacity, Func<TV, TK> getKey = null)
: base(capacity) {
GetKey = getKey;
}
public QueueExt(IComparer<TK> comparer, Func<TV, TK> getKey = null)
: base(comparer) {
GetKey = getKey;
}
public QueueExt(int capacity, IComparer<TK> comparer, Func<TV, TK> getKey = null)
: base(capacity, comparer) {
GetKey = getKey;
}
public QueueExt(IDictionary<TK, TV> dictionary, Func<TV, TK> getKey = null)
: base(dictionary) {
GetKey = getKey;
}
public QueueExt(IDictionary<TK, TV> dictionary, IComparer<TK> comparer, Func<TV, TK> getKey = null)
: base(dictionary, comparer) {
GetKey = getKey;
}
#endregion
public TV Dequeue() {
lock (this) {
var first = this.ElementAt(0).Value;
this.RemoveAt(0);
return first;
}
}
public void Requeue() {
if (GetKey == null)
throw new ArgumentNullException("Key getter lamda must not be null");
lock (this) {
var key = this.ElementAt(0).Key;
var actualkey = GetKey(this.ElementAt(0).Value);
if (!actualkey.Equals(key)) {
this.Enqueue(this.Dequeue());
}
}
}
public void Enqueue(TK key, TV item) {
this.Add(key, item);
}
public void Enqueue(TV item) {
if (GetKey == null)
throw new ArgumentNullException("Key getter lamda must not be null");
var key = GetKey(item);
this.Add(key, item);
}
public TV Peek() {
return this.ElementAt(0).Value;
}
}