A while back I wrote an article about How to sort data by manipulating the view only, This article will handle filtering the data without changing it.


I had a large collection that I needed to display and allow the user to filter it using many parameters. After searching for a while I found a very elegant solution:


What is a Predicate

what are predicates? I will Quote

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

You can read more about it here.


Defining a Predicate

A predicate Is a template so you will have to specify the type for instance:


   1: Predicate<object> prd = new Predicate<object>(SomeFunction);;

Where the “SomeFunction” needs to be of type bool func(object) for instance:

   1: private bool SomeFunction(object p)
   2: {
   3:     if(p is int)
   4:     {
   5:         if((int)p > 0)
   6:         {
   7:             return true;
   8:         }
   9:         else
  10:         {
  11:             return false;
  12:         }
  13:     }
  14:     else
  15:     {
  16:         return false;
  17:     }
  18: }

We are assuming that the collection holds int types, but incase the object is a complex one you can check everything you want inside this predicate.


Using the Predicate

Using it is very simple. All you have to do is specify the predicate to the Items control that displays the data:

   1: private void ApplyScreen_Click(object sender, RoutedEventArgs e)
   2: {
   3:     ItemList.Items.Filter = null;
   4:     ItemsList.Items.Filter = prd;
   5: }

I found that setting the filter to null before applying if will make sure no residue is left from other filters. To remove the filtering all you have to do is just set it to null:

   1: private void ClearScreen_Click(object sender, RoutedEventArgs e)
   2: {
   3:    ItemList.Items.Filter = null;
   4: }

That’s it.


Now you can filter your collection with out having to handle that data.



Tags :

2 Responses to “Filtering Your Data Using Predicates”

  1. Kapa

    Said on December 4, 2008 :

    I can’t get this idea to work in WPF with a ListBox control.
    I’m getting a “Specific method is not supported”-runtime error when I’m binding the predicate with the ItemCollection Filter.

  2. CL

    Said on January 13, 2009 :


    I think your somefunction need to be static. It gave me an error
    “A field initializer cannot reference the non-static field, method, or property”

Post a Comment