CareTaker22 CareTaker22 - 1 year ago 67
C# Question

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

I have a filter that filters out items in an

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)


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

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 Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download