Simo L.
Simo L.

Reputation: 321

How to implement collection filtering based on different criteria

I'm making an Android application where I have a list of items (over 500 entries), and 10 filter buttons (checkboxes), and a seach box.

The user can click on one or many filters and the list is updated accordingly.

Here is how I did it: I start by 10 lists, each initialized by only the items matching a filter, then when the user activates (for instance) the filters 1, 3, and 7, I make an intersection of lists 1, 3 and 7 and then I browse it to filter it against the search query.

I found this to be the "fastest" way so far, but I know there is a better and more efficient pattern. What can you recommend so it takes less time?

Thanks

Upvotes: 4

Views: 875

Answers (1)

Reid Evans
Reid Evans

Reputation: 1641

You could use a collection of strategy patterns.

interface IFilter
{
    List<Item> Filter(List<Item> items);
}

class FilterA implements IFilter
{
    public List<Item> Filter(List<Item> items)
    {
        //filter
    }
}

class FilterB implements IFilter
{
    public List<Item> Filter(List<Item> items)
    {
        //filter
    }
}

//list that would have filters added to it as the user activates filters
List<IFilter> filters = new List<IFilter>();    
//your list of items
List<Item> items = new List<Item>();

public List<Item> Filter() {
    for (IFilter filter : filters) {
        items = filter.Filter(items);
    }    
    return items;
}

Upvotes: 1

Related Questions