2012-03-27 20 views

Respuesta

64

Intente utilizar

collection.Insert(0, item); 

Esto sería añadir el artículo al principio de la colección (mientras Add añade al final). Más información here.

5

Debería usar una pila en su lugar.

Esto se basa en Observable Stack and Queue

Crear una pila observable, donde la pila siempre es el último en la primera en salir (LIFO).

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

Esto exige INotifyCollectionChanged, hace lo mismo que un ObservableCollection, pero de una manera pila.

+0

¿Por qué necesita una pila? ¿No puede sencillamente '.Insertar (0, elemento)' cualquier elemento nuevo al principio de la lista? – ANeves

+1

@ANeves, porque la inserción mencionada se realiza en el tiempo O (n), por lo que puede ser una inserción costosa. – mslot

+0

@mslot si ese es el motivo, debería estar en la respuesta. – ANeves

0

puede probar esta

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

Cuestiones relacionadas