2012-03-27 13 views

risposta

64

Provare a utilizzare

collection.Insert(0, item); 

Questo aggiungerebbe voce per l'inizio della raccolta (mentre Add aggiunge alla fine). Maggiori informazioni here.

5

Si dovrebbe usare invece una pila.

questo si basa su Observable Stack and Queue

Crea uno Stack osservabile, in cui stack è sempre Last In First Out (LIFO).

da 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; } 
    } 
} 

Ciò richiede INotifyCollectionChanged, fa lo stesso come ObservableCollection, ma in maniera pila.

+0

Perché ha bisogno di uno stack? Non può semplicemente semplicemente ".Inserire (0, elemento)" qualsiasi nuovo elemento all'inizio della lista? – ANeves

+1

@ANeves, poiché l'inserto menzionato viene eseguito in tempo O (n), quindi può essere un inserto costoso. – mslot

+0

@mslot se questo è il motivo, dovrebbe essere nella risposta. – ANeves

0

si può provare questo

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

Problemi correlati