2012-03-27 7 views

Antwort

64

Versuchen Sie es mit

collection.Insert(0, item); 

Dieser Artikel an den Anfang der Sammlung hinzufügen würde (während an das Ende hinzufügt). Weitere Informationen here.

5

Sie sollten stattdessen einen Stapel verwenden.

auf Observable Stack and Queue

Eine beobachtbare Stapel, dieser basiert, wo Stapel immer in first out (LIFO) wird dauern.

von Sascha 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; } 
    } 
} 

Dies erfordert INotifyCollectionChanged, tut das gleiche wie ein ObservableCollection, aber in einem Stapel Weise.

+0

Warum braucht er einen Stapel? Kann er nicht einfach einfach '.Insert (0, item)' irgendwelche neuen Gegenstände am Anfang der Liste? – ANeves

+1

@ANeves, Weil der erwähnte Einsatz in O (n) Zeit gemacht wird, so kann es ein teurer Einsatz sein. – mslot

+0

@mslot wenn das der Grund ist, sollte es in der Antwort sein. – ANeves

0

können Sie versuchen, diese

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

Verwandte Themen