.net中的滚动列表

Lou*_*hys 5 .net collections list

.NET中是否有任何列表/集合类,其行为类似于滚动日志文件?用户可以在其中附加元素,但如果超出最大容量,列表将自动删除旧元素.

我还想访问列表中的任何元素,例如list [102]等.

Sim*_*ier 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();
}
Run Code Online (Sandbox Code Playgroud)


小智 0

Microsoft 的标准类不适合您的目的。但你可以观看 Queue<> 课程。
Queue<> 类自动扩展的一个问题。您可以解决该线程中的问题Limit size of Queue<T> in .NET?

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

LogItem result = collection.Where(x => x.ID == 100).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)