Master Your Realm Xamarin – Using Linq Queries

In this lesson

  • Add Xamarin.Forms SearchBar
  • Add Search method to DB Service
  • Use Linq Where clause



In this video, we’re going to use a Realm Xamarin database to search for different record sets that we have stored to the device’s local storage. One of the first things I’m going to do to kick this off is I’m going to add a search bar to our People ListPage. If we run our application we’ll be able to see this new search bar.


Next, we want to go into our PeopleListViewModel and add a property that we can bind to our search bar. I’m going to call this property SearchText. Oops, I need to make our private field lower case and our public declaration upper case. I’m going to copy and paste this PropertyChanged statement which will make sure our bindings work correctly. Next, I’m going to go into our IDBService class interface. I’m going to create a new method called SearchPeople that returns a list of persons and takes a strings of search text as a parameter.


If we go into our RealmDBService, we’ll see that Intellisense is telling us that we haven’t implemented our interface correctly. I’m going to add the SearchPeople method. I’m going to copy and paste our previous GetPeople method body text and we’re going to add a Where Linq clause. I’m basically going to say return any persons whose first name contains the search text or anyone whose last name contains the search text. Now if we run our application, we’ll check to see if we get any sort of run time errors.


We’ll see as we type, nothing happens. So I’m going to go into PeopleListViewModel and double check that everything is good there. The reason we don’t see any changes in our text, is we forget to update our People ObservableCollection any time the search text is set. Here again, I need to wrap our results with an ObservableCollection.


Now, if we run our application, we will still see that we’re not getting any changes in our ListView because we forgot to bind our search text to our actual search text property in our ViewModel. We’re now going to go into our People page XAML and I’m going to bind the text of the search bar to our ViewModel property search text.


Now, when I run the application for the fifth time, it should work as intended. As you can see, as I type, we filter our results in real time. Because Realm Xamarin is based on Linq it is very easy to write queries for our Xamarin.Forms application.

Additional Info

Register to get access to additional resources and info.