0

I often need to filter an ObservableCollection that already have items in it. Which approach is better?

// Assigning the filtered result directly
FilteredObservableCol = FilteredCollectionCopy.Where(i=> i.Age > 25).ToObservableCollection();

Or

// Clearing the collection first
FilteredObservableCol.Clear();
FilteredObservableCol = FilteredCollectionCopy.Where(i=> i.Age > 25).ToObservableCollection();
usefulBee
  • 8,652
  • 9
  • 48
  • 78

1 Answers1

2

You could use CollectionViewSources instead of the ObservableCollection to bind to. There you can apply filtering.

ICollectionView MyCollection { get; private set; }

public void LoadData()
{
    var myObservable = //... load/create list
    MyCollection = CollectionViewSource.GetDefaultView(myObservable);
    MyCollection.Filter = item => ((TypeOfItem)item).Name = "bob";
}
Michael Mairegger
  • 6,503
  • 28
  • 40