【问题标题】:List which automatically removes the oldest item when I add a new one添加新项目时自动删除最旧项目的列表
【发布时间】:2015-03-02 16:48:40
【问题描述】:

我需要一个 C# 类来存储 不超过最后 N 个项目,方法如下:

Add(T item) {
    if (mylist.Count >= N)
        remove the first(oldest) item;
    add a new item to the tail;
}

并且具有在指定索引处获取项目的属性。
所以可能正确的方法是让我的类基于以下类之一:List、Queue、ConcurrentQueue、Dequeue(可能有所不同?)。当然,一个类应该为头部和尾部提供相等的访问时间。
问题是,什么类最适合我的目的?

【问题讨论】:

  • 对头部和尾部的访问时间相等。听起来像是常规列表的子类
  • List<T> 是否为其头部和尾部提供相同的访问时间?
  • 这取决于您要存储的元素数量。 Here 是一个比较。对于 smaller n 或进行大量 lookups List 就可以了。对于大 n 其他人可能会更好..
  • 是的,这确实是一个有趣的参考,但我仍然看不到我需要什么。而List 不存储指向其尾部的链接,因此效率为 o(n)。

标签: c# list queue


【解决方案1】:

使用 LinkedList(t) 来做到这一点。这为您提供了 First、Last 和 Count。这样,一旦计数达到某个点,就可以删除最后一个。

myList = new LinkedList();

Add(T item){
    if (myList.Count >= N)
        myList.RemoveLast();
    myList.AddFirst(item);
}

在这种情况下,最后一项是最旧的,第一项是最新的。

【讨论】:

  • 嗯...我不想无聊,但是'LinkedList'对我来说太多了,我实际上不需要每个节点中的前一个节点的链接。
【解决方案2】:

所以我报告了我的研究。 C# 中的List<T> 类实际上是一个向量,而不是计算机科学中定义的列表。 LinkedList<T> 确实是一个列表,但是是双向链接的。
我编写了非常简单的类来解决我的任务。

/// <summary>
/// Fixed-size buffer. When the buffer is full adding a new item removes the first item,
/// so buffer stores the last N (where N is a size) adding items.
/// Reading is provided by indexing, rewriting isn't allowed.
/// Buffer could be changed by using method Add only.
/// </summary>
public class RingBuffer<T> {
    int size;
    T[] ringbuffer;
    int i0 = 0, count = 0;

    int getIndex(int i) {
        int k=i0+i;
        return k < count ? k : k-size;
    }
    public RingBuffer(int size) {
        this.size = size;
        ringbuffer = new T[size];
    }
    public int Count {
        get { return count; }
    }
    public bool isFull {
        get { return count == size; }
    }
    public T this[int i] {
        get { return ringbuffer[getIndex(i)]; }
    }
    public void Add(T item) {
        if (isFull)
            // rewrite the first item
            ringbuffer[i0++] = item;
        else
            ringbuffer[count++] = item;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多