如何在ObservableCollection的开头插入一个项目?

Jas*_*n94 42 c#

我怎样才能做到这一点?我需要一个列表(类型ObservableCollection),其中最新项目是第一个.

Dmi*_*nik 86

尝试使用

collection.Insert(0, item);
Run Code Online (Sandbox Code Playgroud)

这会将项目添加到集合的开头(而Add添加到结尾).更多信息在这里.


Kev*_*vin 8

你应该使用堆栈代替.

这基于Observable Stack and Queue

创建一个可观察的堆栈,其中堆栈始终是先进先出(LIFO).

来自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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会调用INotifyCollectionChanged,与ObservableCollection相同,但是以堆栈方式执行.

  • @ANeves,因为上述插入是在O(n)时间完成的,所以它可能是一个昂贵的插入。 (2认同)