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.
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();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With