In a WPF application, I've a list of object.
We will add a lot of element inside this list regularly(~1-10 items/seconds).
We want to add a "capacity" to this list, in order that when we reach this capacity, we remove the "oldest" item added.
This list will be bound to a WPF UserControl, so it needs to be ObservableCollection
or similar.
But, my understanding is that a Collection
doesn't garantee the order, so I cannot do the following:
int nbOfElementsToRemove = EventsList.Count - MAX_EVENTS;
if (nbOfElementsToRemove > 0)
{
LoggingEvent[] loggingEvents = EventsList.Take(nbOfElementsToRemove).ToArray();
foreach (LoggingEvent loggingEvent in loggingEvents)
{
EventsList.Remove(loggingEvent);
}
}
Because I will maybe not get the oldest items.
So what is the most efficient way of removing the oldest item(s) of a list that has to be bound to a WPF usercontrol?
An ObservableCollection
is indeed an ordered collection, so you should have no problem removing the oldest one through a variety of means.
If you're simply adding items through EventsList.Add()
then you can remove the first item in the collection: EventsList.RemoveAt(0)