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.

4

2 回答 2

8

这是一个简单的实现:

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();
}
于 2013-08-23T13:25:44.650 回答
0

Microsoft 的标准类不存在于您的目的。但是您可以观看 Queue<> 类。
Queue<> 类自动扩展的一个问题。您可以在 .NET 中的 Queue<T> 的线程限制大小中解决它的问题吗?

可以通过扩展方法访问任何元素。例如:

LogItem result = collection.Where(x => x.ID == 100).FirstOrDefault();
于 2013-02-05T09:11:30.203 回答