Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling list in .net

Is there any list/collection class in .NET that behaves like a rolling log file? The user can append elements into it, but the list will automatically delete old elements if maximum capacity is exceeded.

I also want access to any element to the list, e.g. list[102], etc.

like image 919
Louis Rhys Avatar asked Feb 05 '13 08:02

Louis Rhys


1 Answers

Here is a simple implementation for this:

public class RollingList<T> : IEnumerable<T>
{
    private readonly LinkedList<T> _list = new LinkedList<T>();

    public RollingList(int maximumCount)
    {
        if (maximumCount <= 0)
            throw new ArgumentException(null, nameof(maximumCount));

        MaximumCount = maximumCount;
    }

    public int MaximumCount { get; }
    public int Count => _list.Count;

    public void Add(T value)
    {
        if (_list.Count == MaximumCount)
        {
            _list.RemoveFirst();
        }
        _list.AddLast(value);
    }

    public T this[int index]
    {
        get
        {
            if (index < 0 || index >= Count)
                throw new ArgumentOutOfRangeException();

            return _list.Skip(index).First();
        }
    }

    public IEnumerator<T> GetEnumerator() => _list.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
like image 115
Simon Mourier Avatar answered Oct 10 '22 03:10

Simon Mourier