Ограниченный размер IList <T>или ICollection <T>, что при добавлении нового элемента первый элемент отбрасывается - PullRequest
1 голос
/ 16 сентября 2011

Я ищу какую-то реализацию IList<T> или ICollection<T>, которая ведет себя таким образом, что может содержать до определенного количества элементов.

Если добавление нового элемента превысит предельную сумму, первый элемент должен быть автоматически удален, чтобы освободить место для вновь добавленных.

1 Ответ

3 голосов
/ 16 сентября 2011

Без дополнительной информации о требованиях (память, количество операций чтения, количество операций записи и т. Д.) Приведем базовую реализацию:

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();
    }
}
...