EnqueueWithCapacity

public static void EnqueueWithCapacity<T>(this Queue<T> q, T item, int MaxSize)
{
	if(q.Count >= MaxSize) q.Dequeue();
	q.Enqueue(item);
}
Example:
Queue<int> q = new Queue<int>();
q.EnqueueWithCapacity(0, 3); // {0}
q.EnqueueWithCapacity(1, 3); // {0, 1}
q.EnqueueWithCapacity(2, 3); // {0, 1, 2}
q.EnqueueWithCapacity(3, 3); // {1, 2, 3}

Description

Sometimes you may need a Queue<T> that, once it hits a capacity, dequeues items automatically to maintain a certain maximum. While it may be best to derive a new type from Queue<T>, this will get it done much more quickly. This is very useful for maintaining a rolling average or a "history" feature.

Details

Double click on the code to select all.

 

;