2

Possible Duplicate:
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?

Community
  • 1
  • 1
A.R.
  • 15,405
  • 19
  • 77
  • 123

4 Answers4

5

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
        }
    }
}
Alex Aza
  • 76,499
  • 26
  • 155
  • 134
0

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);
        }
    }
FIre Panda
  • 6,537
  • 2
  • 25
  • 38
-1

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

Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
-1

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.

Sujay Ghosh
  • 2,828
  • 8
  • 30
  • 47