.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/