7

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.

Louis Rhys
  • 30,777
  • 53
  • 137
  • 211

2 Answers2

7

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();
}
Simon Mourier
  • 117,251
  • 17
  • 221
  • 269
0

Standart class from Microsoft not exist for you purpose. But you can watch Queue<> class.
One problem that Queue<> class auto expand. You can resolve it problem in that thread Limit size of Queue<T> in .NET?

Access to any element able by extended method. For example:

LogItem result = collection.Where(x => x.ID == 100).FirstOrDefault();
Community
  • 1
  • 1
Alexey
  • 39
  • 3