How to filter a list - Rudi Grobler
Tuesday, June 19, 2007 10:51 AM rudi

How to filter a list

I have a list of blogs and I want to be able to filter these items by just typing leters contained in the title of these blogs and the list box must then only show the items which contains these leters...

I started by creating a List<string> of blogs

List<string> blogs;

The next step is to initialize this list and add some content...

blogs = new List<string>();
blogs.Add("Zlatan's Blog ");

My WPF window contains a TextBox names txtSearch and a ListBox named lbItems. Next, you have to bind the blogs list to the ListBox

lbItems.ItemsSource = blogs;

Now is a good time to save and test. A list of all the blogs previously added should now be displayed. Next step is to add a ICollectionView

ICollectionView view;

Next we have to find the defualt view for this array

view = CollectionViewSource.GetDefaultView(blogs);

We also need to add two delegates, the first delegate is for Filter


view.Filter = delegate(object obj
{
    
if string.IsNullOrEmpty(txtSearch.Text))
      
return true
    
string str obj.ToString();
    
if (string.IsNullOrEmpty(str)) 
      
return false;

    
int index str.IndexOftxtSearch.Text0StringComparison.InvariantCultureIgnoreCase); 
    
return index > -1
};

This delegate checks the provided item if it contains any part of the provided search string (txtSearch). Lastly, we need to add another delegate for the TextChanged event of the txtSearch to refresh the view

txtSearch.TextChanged += delegate
{
    view.Refresh
();
};

And that is all that is needed to automatically filter the items based on the provided part of text.

Filed under:

Comments

# re: How to filter a list

Wednesday, June 20, 2007 12:31 AM by Craig Nicholson

As a note, isn't this considered unsafe code considering that txtSearch.Text can change whilst the filter delegate is executing?

# re: How to filter a list

Wednesday, June 20, 2007 8:21 AM by rudi

Well spotted craig, yes... this might be a little unsafe:-)

To make this safer, you might want to store the content of txtSearch into a temporary string and use this temporary sting for the comparisons.. then call refresh. You should also check not to call refresh until it has finished running the previous time?