What I need is a collection where i can specify the max number of elements. If i try to insert an element and the collection is full. The first element in the collection is removed, so that it does not overflow.
Is there such an object in .net or开发者_StackOverflow社区 do i have to make it myself?
You can extend Queue class in order to do it.
For example:
public class MaxQueue : Queue
{
private int maxItems;
public MaxQueue(int maxItems)
{
this.maxItems = maxItems;
}
public override void Enqueue(object obj)
{
if(Count == maxItems)
{
Dequeue();
}
base.Enqueue(obj);
}
}
(this example is very naive. It is not thread safe, it doesn't check the maxItems is at least 1. It is based on Queue so you're safe to know you dequeued the first item added to it)
There is no existing collection in .NET that provides a circular/cyclic buffer implementation. You will have to roll it yourself.
Also, see a related question on SO here: How would you code an efficient Circular Buffer in Java or C#
精彩评论