Filtering Data (using ICollectionView)

The ICollectionView interface also includes support for filtering data through its Filter property. The Filter property specifies a method that is called for each item in the collection. If the method returns true, the item is included in the view. If the method returns false, the item is filtered out of view. (This type of method is called a predicate).

The MainTestApplication sample included with this document includes a SearchBox control that consists of a TextBox control where the user types a value to search for and a timer. The timer provides a small delay to allow users to type the values to search for without re-applying the filter after each character.

When the user stops typing, the timer elapses and applies the filter using this code:

_view.Filter = null;
_view.Filter = (object item) =>
{
  var srch = _txtSearch.Text;
  if (string.IsNullOrEmpty(srch))
  {
    return true;
  }
  foreach (PropertyInfo pi in _propertyInfo)
  {
    var value = pi.GetValue(item, null) as string;
    if (value != null &&
        value.IndexOf(srch, StringComparison.OrdinalIgnoreCase) > -1)
    {
      return true;
    }
  }
  return false;
};

Note how the code sets the value of the Filter property using a lambda function. We could just as easily have provided a separate method, but this notation is often more convenient because it is concise and allows us to use local variables if they are needed.

The lambda function takes an item as a parameter, gets the value of the specified properties for the object, and returns true if any of the object's properties contain the string being searched for.

For example, if the objects were of type "Song" and the properties specified were "Title", "Album", and "Artist", then the function would return true if the string being searched for were found in the song's title, album, or artist. This is a powerful and easy-to-use search mechanism similar to the one used in Apple's iTunes application.

As soon as the filter is applied, the grid (and any other controls bound to the ICollectionView object) will reflect the result of the filter by showing only the items selected by the filter.

Note that filtering and grouping work perfectly well together. The image below (from the MainTestApplication sample) shows a very large song list with a filter applied to it:

The image shown was taken when the filter was set to the word “Water”. The filter looks for matches in all fields (song, album, artist), so all “Creedence Clearwater Revival” songs are automatically included.

Notice the status label displayed above the grid. It is automatically updated whenever the list changes, so when the filter is applied the status is updated to reflect the new filter. The routine that updates the status uses LINQ to calculate the number of artists, albums, and songs selected, as well as the total storage and play time. The song status update routine is implemented as follows:

// update song status
void UpdateSongStatus()
{
  var view = _flexiTunes.ItemsSource as ICollectionView;
  var songs = view.OfType<Song>();
  _txtSongs.Text = string.Format(
     "{0:n0} Artists; {1:n0} Albums; {2:n0} Songs; " +
     "{3:n0} MB of storage; {4:n2} days of music.",
    (from s in songs select s.Artist).Distinct().Count(),
    (from s in songs select s.Album).Distinct().Count(),
    (from s in songs select s.Name).Count(),
    (double)(from s in songs select s.Size/1024.0/1024.0).Sum(),
    (double)(from s in songs select s.Duration/3600000.0/24.0).Sum());
}

This routine is not directly related to the grid, but is listed here because it shows how you can leverage the power of LINQ to summarize status information that is often necessary when showing grids bound to large data sources.

The LINQ statement above uses the Distinct and Count commands to calculate the number of artists, albums, and songs currently exposed by the data source. It also uses the Sum command to calculate the total storage and play time for the current selection.


Send us comments about this topic.
Copyright © GrapeCity, inc. All rights reserved.