ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

EnqueueWithCapacity

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.

Source

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}

Author: David Harris

Submitted on: 21 aug 2010

Language: C#

Type: System.Collections.Generic.Queue<T>

Views: 4554