Possible D开发者_开发问答uplicate:
Fixed size queue which automatically dequeues old values upon new enques
Is there such a thing as a collection that will automatically drop old items as new items are added? Let's say that I have a list that is limited to ten items. Upon adding an eleventh item, the first is removed, and the capacity remains at ten. Seems like there would be such a thing, but I can't find it. Any ideas?
One possible way to achieve your goal:
public class FixedSizedQueue<T> : Queue<T>
{
private readonly int maxQueueSize;
private readonly object syncRoot = new object();
public FixedSizedQueue(int maxQueueSize)
{
this.maxQueueSize = maxQueueSize;
}
public new void Enqueue(T item)
{
lock (syncRoot)
{
base.Enqueue(item);
if (Count > maxQueueSize)
Dequeue(); // Throw away
}
}
}
You could achieve this through custom coding, have a look at
//Lets suppose Customer is your custom class
public class CustomerCollection : CollectionBase
{
public Customer this[int index]
{
get
{
return (Customer) this.List[index];
}
set
{
this.List[index] = value;
}
}
public void Add(Customer customer)
{
if(this.List.Count > 9)
this.List.RemoveAt(0);
this.List.Add(customer);
}
}
AFIK, such a collection does not exist. You are going to have to roll your own. One possibility is deriving from ObservableCollection<T>
and use the CollectionChanged
event to remove "old" items
The above answers are correct ; you have to write your own code .
However , you can acheive this using reference counting . The link says how .NET does the garbage collection through reference counting. This is not required for a simple question like this, but it shall proabably help you in the long run.
精彩评论