Question

I'm looking for some sort of implementation of IList<T> or ICollection<T> that behaves in such a way that it can hold up to a specified amount of items.

If adding a new item would exceed the limit-amount, the first item should be automatically discarded to make room for the newly added ones.

Était-ce utile?

La solution

Without much more information regarding the requirements (memory, number of reads, number of writes, etc) here's a very basic implementation:

class CircularList<T> : ICollection<T>
{
    private readonly int capacity;
    private readonly LinkedList<T> list;

    public CircularList(int capacity)
    {
        this.capacity = capacity;
        this.list = new LinkedList<T>();
    }

    public int Count
    {
        get { return this.list.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public void Add(T item)
    {
        if (this.list.Count == this.capacity)
            this.list.RemoveFirst();

        this.list.AddLast(item);
    }

    public void Clear()
    {
        this.list.Clear();
    }

    public bool Contains(T item)
    {
        return this.list.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        this.list.CopyTo(array, arrayIndex);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this.list.GetEnumerator();
    }

    public bool Remove(T item)
    {
        return this.list.Remove(item);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top