How to Remove Duplicates from ICollectionView using FilterEventArgs MVVM

312 views Asked by At

I have two Properties in my Vehicle Model: Category and Name.

I have an ICollectionView called VehiclesView.

When bound to Category, the ListView displays:

Airplane
Helicopter
Helicopter
Airplane
Car
Car

I must be able to filter the VehiclesView to remove duplicates of the same Category which will result in:

Airplane
Car
Helicopter

Requirement: The filtering logic must use FilterEventArgs, like this:

 public void ApplyFilter(object sender, FilterEventArgs e)
    {
        Vehicle v = e.Item as Vehicle;
        if (v != null)
        {
            // Remove duplicate instances of Category
            if (??????????????)
            {
                e.Accepted = false;
            }
            else
            {
                e.Accepted = true;
            }
        }
    }

I only need help with the Filtering Logic.

Any help is greatly appreciated.

EDIT 1: 'Category' is user defined, which means the filter must compare the property values at runtime and remove the duplicates.

EDIT 2: Added links to all research performed, none of which provide the Filter logic I require, but do offer other types of filtering logic and the "Big picture" of how to implement filtering/sorting/grouping.

https://weblogs.asp.net/monikadyrda/wpf-listcollectionview-for-sorting-filtering-and-grouping

http://wpftutorial.net/DataViews.html

C# - how to get distinct items from a Collection View

https://social.technet.microsoft.com/wiki/contents/articles/26673.wpf-collectionview-tips.aspx

http://www.abhisheksur.com/2010/08/woring-with-icollectionviewsource-in.html

Implementing a ListView Filter with Josh Smith's WPF MVVM Demo App

http://www.codewrecks.com/blog/index.php/2011/02/23/filtering-in-mvvm-architecture/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+AlkampferEng+%28Alkampfer%27s+Place%29&utm_content=Google+Reader

1

There are 1 answers

2
BionicCode On

You can create a lookup table:

private HashSet<object> ExistingItemsTable { get; } = new HashSet<object>();
private void ApplyFilter(object sender, FilterEventArgs e)
{
  if (this.ExistingItemsTable.Contains(e.Item))
  {
    // FilterEventArgs.Accepted is true by default
    e.Accepted = false;
    return;
  }

  this.ExistingItemsTable.Add(e.Item);
}

You need to subscribe to the CollectionChanged event of the source collection to maintain the lookup table: when items are removed you also need to remove them from the table.