In this short tutorial I show how to use Linq in order to filter the items shown in a listbox, which in turn is databound to an ObservableCollection.
Suppose we use the listbox created in the previous tutorial where we show the age and name of each user in the collection. All our databinding code-remains the same as before. What we have to add is a new collection in between our original source and the listbox. The in between collection is our Linq-query result. Each time we wish to change our filter, we change the query.
So suppose we wish to bind to the complete collection, we’d write the following query:
new ObservableCollection<User>(from u in Users select u);
If at some point we’d like to filter out data and for example only show users whose age is greater than 25 we simple change the ItemsSource:
lbUsers.ItemsSource =new ObservableCollection<User>
(from p in Users where p.Age > 25 select p);