2015-03-02 50 views
1

我需要在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(可能是不同的東西?)。當然,一個班級應該爲頭部和尾部提供平等的訪問時間。
問題是,什麼樣的課程最適合我的目的?

+1

_equal訪問時間的頭和tail._聽起來就像從常規列表 TaW 2015-03-02 17:04:18

+0

是否'名單'它的頭和尾巴提供平等的接入時間的子類? – Vikora 2015-03-02 20:58:14

+0

那它取決於你想存儲的元素的數量。 [Here](http://geekswithblogs.net/BlackRabbitCoder/archive/2011/06/16/c.net-fundamentals-choosing-the-right-collection-class.aspx)是一個比較。對於__smaller n__或做大量__lookups__名單會很好。對於大n其他人可能會更好.. – TaW 2015-03-02 21:23:37

回答

1

使用LinkedList(t)來做到這一點。這給了你一個,最後一個和計數。這樣一旦計數達到某個點,最後一個可以被刪除。

myList = new LinkedList(); 

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

在這種情況下,最後一個項目是最老的,第一個項目是最新的。

+0

嗯......我不想無聊,但'LinkedList'對於我的目的來說太多了,實際上我並不需要鏈接到每個節點中的前一個節點。 – Vikora 2015-03-02 18:50:04

0

所以我報告我的研究。在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; 
    } 
} 
相關問題