Using Linq to filter a databound listbox in WPF/Silverlight

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:

lbUsers.ItemsSource =

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);

About these ads

About timdams
C#, .NET, Microsoft, security, .... Read more on : http://timdams.com/

2 Responses to Using Linq to filter a databound listbox in WPF/Silverlight

  1. George says:

    Thanks man, your post helped me a lot!
    To add info: Multiple “where” conditons

    lbUsers.ItemsSource =new ObservableCollection
    (from p in Users where p.Age > 25 && p.Age <70 select p);

    lbUsers.ItemsSource =new ObservableCollection
    (from p in Users where p.Age > 25 || p.Name ==”Mary” select p);

  2. anon says:

    it say “where” can no be resolved?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 329 other followers

%d bloggers like this: