2012-03-27 41 views

回答

64

嘗試使用

collection.Insert(0, item); 

這將增加項目到集合的開始(而添加添加到結束)。更多信息here

5

您應該使用堆棧。

這是基於Observable Stack and Queue

創建一個可觀察的堆棧,其中堆棧總是倒數第一的出(LIFO)。

從霍爾的Sascha

public class ObservableStack<T> : Stack<T>, INotifyCollectionChanged, INotifyPropertyChanged 
{ 
    public ObservableStack() 
    { 
    } 

    public ObservableStack(IEnumerable<T> collection) 
    { 
     foreach (var item in collection) 
      base.Push(item); 
    } 

    public ObservableStack(List<T> list) 
    { 
     foreach (var item in list) 
      base.Push(item); 
    } 


    public new virtual void Clear() 
    { 
     base.Clear(); 
     this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); 
    } 

    public new virtual T Pop() 
    { 
     var item = base.Pop(); 
     this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item)); 
     return item; 
    } 

    public new virtual void Push(T item) 
    { 
     base.Push(item); 
     this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); 
    } 


    public virtual event NotifyCollectionChangedEventHandler CollectionChanged; 


    protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
     this.RaiseCollectionChanged(e); 
    } 

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
     this.RaisePropertyChanged(e); 
    } 


    protected virtual event PropertyChangedEventHandler PropertyChanged; 


    private void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
     if (this.CollectionChanged != null) 
      this.CollectionChanged(this, e); 
    } 

    private void RaisePropertyChanged(PropertyChangedEventArgs e) 
    { 
     if (this.PropertyChanged != null) 
      this.PropertyChanged(this, e); 
    } 


    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged 
    { 
     add { this.PropertyChanged += value; } 
     remove { this.PropertyChanged -= value; } 
    } 
} 

這要求INotifyCollectionChanged,做同樣的作爲的ObservableCollection,但在一個堆棧方式。

+0

爲什麼他需要一個堆棧?他不能只是簡單的'。插入(0,項目)'列表開始的任何新項目? – ANeves 2014-04-02 10:58:15

+1

@ANeves,因爲所提到的插入是在O(n)時間完成的,所以它可能是一個昂貴的插入。 – mslot 2014-04-14 20:20:35

+0

@mslot如果是這樣的原因,它應該在答案。 – ANeves 2014-04-15 00:05:04

0

你可以試試這個

collection.insert(0,collection.ElementAt(collection.Count - 1));