2012-03-27 42 views

答えて

64

は、(追加は、最後に追加しながら)これはコレクションの先頭に項目を追加します

collection.Insert(0, item); 

を使用してみてください。詳細情報here

5

代わりにスタックを使用する必要があります。

これは、スタックは常に最初で最終れる観測可能なスタック(LIFO)を作成しますObservable Stack and Queue

に基づいています。サシャHOLLから

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

なぜ彼はスタックが必要ですか?リストの先頭に新しいアイテムがあれば、単に '.Insert(0、item)'することはできないのですか? – ANeves

+1

@ANeves、上記の挿入はO(n)時間で行われるので、高価な挿入物になる可能性があります。 – mslot

+0

@mslotそれが理由なら、それは答えにあるはずです。 – ANeves

0

あなたはこの

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

関連する問題