How can I do that? I need a list (of type ObservableCollection
) where the latest item is first.
3 Answers
Try using
collection.Insert(0, item);
This would add item to the beginning of the collection (while Add adds to the end). More info here.
-
-
this method is O(n), so it not recommended for large collections. learn.microsoft.com/en-us/dotnet/api/… Commented Jan 27, 2022 at 5:47
You should use a stack instead.
This is based on Observable Stack and Queue
Create an observable Stack, where stack is always last in first out (LIFO).
from 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; }
}
}
This calls INotifyCollectionChanged, does the same as a ObservableCollection, but in a stack manner.
-
Why does he need a stack? Can't he just simply
.Insert(0, item)
any new items in the beginning of the list?– ANevesCommented Apr 2, 2014 at 10:58 -
2@ANeves, Because the mentioned insert is done in O(n) time, so it can be an expensive insert.– mslotCommented Apr 14, 2014 at 20:20
-
1
-
I tried using this observable stack as a datasource for my listbox, but it doesn't work. Pushing items is not reflected on the listbox as observable collection usually do, any idea?– NadaNKCommented Jun 24, 2015 at 7:17
you can try this
collection.insert(0,collection.ElementAt(collection.Count - 1));