Search code examples
c#generic-collections

Filter ObservableCollection by ICollectionView and use it


I want to be able to filter my ObservableCollection based on user filtering criteria. At the moment i have datagridview which used this collection in virtual mode:

private ObservableCollection<WarehouseReadModel> _warehouse = new ObservableCollection<WarehouseReadModel>();

Is there any way to use instead ICollectionView? For instance when program starts it shows all data from _warehouse but when any filtering from GUI is done to assign it somehow to ICollectionView or even from begining to assign instead to ICollectionView without any filters and then apply filters when users wants it? If possible please of working example.


Solution

  • You can have two ObservableCollection properties (or fields) :

    public ObservableCollection<WarehouseReadModel> AllWareHouses { get; set}
    public ObservableCollection<WarehouseReadModel> DisplayWareHouses {get; set}
    

    In the beginning, you will load all data in the first property "AllWareHouses". When the user selects any filters, you will filter "AllWareHouses" with a LINQ query for instance.

    The result of the query will be assigned to "DisplayWareHouses". you will use this property to bind to your DataGrid.

    DisplayWareHouses = AllWareHourse.Where(...)