CareTaker22 CareTaker22 - 1 month ago 9
C# Question

Filter out results in a collection without removing them from the collection

I have a filter that filters out items in an

ObservableCollection
so that only certain items in the collection are displayed in my datagrid. The OC is called MyTruckCollection.

The only way that I can filter out results is by removing the items that I do not want and only adding the items that I do want. (I cannot hide certain items in the collection)

Example:

var filteredList = MyTruckCollection.Where(x => x.TruckStatus == filterValue).ToList();
MyTruckCollection.Clear();
foreach (var filteredItem in filteredList)
MyTruckCollection.Add(filteredItem);


Now my issue is that I do not want to remove the items that I do not want from the list, because when I add another filter, the collection only contains the items that was added by the previous filter. So the list of items in my collection is getting smaller and smaller with every filter that I add.

So the question is: Is there a way to filter out certain items in my OC without removing them and still update my datagrid's UI.

I can do this as well:

dgMyTruckCollection.ItemSource = MyTruckCollection.Where(x => x.TruckStatus == filterValue);


But then I loose access to my collection if I want to apply a Sorting function to it and the UI does not get updated. I am not too good with MVVM and do not know much about it, so if someone can help me please?

Answer

You can use ICollectionView interface for the filtering/sorting task. Would be something like this

ICollectionView MyTruckCollectionView= CollectionViewSource.GetDefaultView(MyTruckCollection);
MyTruckCollectionView.Filter = o => ((Truck)o).TruckStatus==filterValue
MyTruckCollectionView.SortDescriptions.Add(new SortDescription("field", ListSortDirection.Ascending));
....