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

2 gedachten over “Using Linq to filter a databound listbox in WPF/Silverlight

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

    Like

  2. it say “where” can no be resolved?

    Like

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit /  Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit /  Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit /  Bijwerken )

Verbinden met %s

Deze site gebruikt Akismet om spam te bestrijden. Ontdek hoe de data van je reactie verwerkt wordt.

%d bloggers liken dit:
search previous next tag category expand menu location phone mail time cart zoom edit close