.net - .net 中的滚动列表

标签 .net list collections

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

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

最佳答案

这是一个简单的实现:

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();
}

关于.net - .net 中的滚动列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14702654/

相关文章:

c++ - 指向指针赋值的指针

java - 显示对象列表

java - 自定义列表类,如何循环hasNext方法?

c# - 如何洗牌 List<T>

c# - 将 Javascript 数组转换为 C# 列表

c# - 从 ASP.NET Web API 层使用的方法中抛出或不抛出异常

c# - 使用 BindingOperations.EnableCollectionSynchronization

c# - 如何使用 LINQ 查找和删除集合中的重复对象?

c# - 如何在 ASP.NET MVC 中使用 GET 请求发送 Content-Type header ?

.net - 在 .NET 中,Array 只扩展了 IEnumerable,那么当 foreach 循环经过值类型数组时,是否会有装箱和拆箱?