Press "Enter" to skip to content

Filtering and sorting with Dynamic Data in Xamarin Forms (Part 2)

In the first part of the series about Dynamic Data I covered how to start with it by adding, editing and deleting items. In this part we are going to see how easy is to filter and sort items.

How to filter

We are going to extend our restaurant list sample by adding a SearchBar to be able to filter by the restaurant name or type.

To achieve this, I’ll use ReactiveUI, so the first step will be to install the ReactiveUI package:

Note: You don’t need ReactiveUI for filtering items with Dynamic Data, but it will make your life easier and is very handy in these scenarios.

2. In the ViewModel create a SearchText property and extend from ReactiveObject

3. Create a filter function

Since I want to filter by name and type, I will compare against these fields so that if there is a matching restaurant, it returns true.

4. Create an Observable to observe the SearchText value changes and call the filter function when it changes

As you see here I’m using Throttle, which will wait for the seconds specify to actually apply the filter function, it helps to reduce the function calls, which improves performance.

5. Pass the Observable to the filter method in the DynamicData list pipeline

6. Add the SearchBar to the UI and bind it to the SearchText property

Done! Check the full ViewModel here.

Applying multiple filters

Let’s extend this to apply multiple filters, so in addition to Search, we also want to filter by an option selected in a picker.

1. Add a picker and options to the UI

2. Follow the same steps we did in the previous section

  • Create a filter function
  • Create an observable to detect when the picker changes
  • Pass the observable to the Filter method in the DynamicData list pipeline

In this specific case, we will use the picker to filter restaurants by country.

How to sort

Let’s now add an option to sort by name or type.

1. In the UI let’s add a Toolbar item for the sort option which Command will bind to a SortCommand

2. Add the SortCommand in the ViewModel which calls an ActionSheet that displays sort options and then assigns the option selected to a SortBy property

3. Create an observable that observes the SortBy property and returns a sort expression.

4. Pass the observable to the sort method in the DynamicData list pipeline

If you haven’t fallen in love with DynamicData yet, stay tuned for the next part of this series about Grouping, where you’ll see how easy it is to group items.

Check the full source code here.

Happy Dynamic Data!