Filtering a collection based on filtering rules

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2013-07-01T16:20:05Z Indexed on 2013/07/01 17:07 UTC
Read the original article Hit count: 473

Filed under:
|

I have an observable collection of Entities, with each entity having a status added, deleted, modified and cancelled.

I have four buttons (toggle) when clicked should filter my collection as below:

  • If I select the button Added, then my collection should contain entities with status added.
  • If I select the button Deleted and Added, then my collection should contain entities with status Deleted AND entities with status Added, none of the rest.
  • If I select the button Deleted,Added and Modified, then my collection should contain entities with status Deleted, Added AND Modified. . . so on.
  • If I unselect one of the buttons, it should remove those entities from the collection with that status. For example if I unselect Deleted, but select Added and Modified, then my collection should contain items with Added and Modified status and NOT Deleted ones.

For implementing this I have created a master collection and a filtered collection. The Filter collection gets filtered based on the selections and unselections. The following is my code:

private bool _clickedAdded;
    public bool ClickedAdded
    {
        get { return _clickedAdded; }
        set
        {
            _clickedAdded = value;
            if(!_clickedAdded)
                FilterAny(typeof(Added));

        }
    }

    private bool _clickedDeleted;
    public bool ClickedDeleted
    {
        get { return _clickedDeleted; }
        set
        {
            _clickedDeleted = value;
            if (!_clickedDeleted)
                FilterAny(typeof(Deleted));
        }
    }

    private bool _clickedModified;
    public bool ClickedModified
    {
        get { return _clickedModified; }
        set
        {
            _clickedModified = value;
            if (!_clickedModified)
                FilterAny(typeof(Modified));
        }
    }

    private void FilterAny(Type status)
    {
        Func<Entity, bool> predicate = entity => entity.Status.GetType() != status;

        var filteredItems = MasterEntites.Where(predicate);
        FilteredEntities = new ObservableCollection<Entity>(filteredItems);
    }

This however breaks the above rules - for example if I have all selected, and then I remove Added followed by deleted then it still shows the list of Added, Modified and Cancelled. It should be just Modified and Cancelled in the filtered collection.

Can you please help me in solving this issue? Also do I need 2 different list to solve this. Please note that I'm using .NET 3.5.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ