ObservableCollection Filtering

Collection: WhereObservatorCollection<T>
Extension method: ObservatorCollectionExtensions.Where(source, predicate)

Description

This collection listens to an IObservableCollection<T> to build a new observable collection filtering the original items using the predicate.

Example

The following example shows how create an observable collection filtering a list of products where only the available products will be visible.

using System.ComponentModel;
using ZumtenSoft.WpfUtils.Collections;

public class Product : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }

    private int _nbAvailable;
    public int NbAvailable
    {
        get { return _nbAvailable; }
        set
        {
            if (_nbAvailable != value)
            {
                _nbAvailable = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("NbAvailable"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Once this is completed, simply use the Linq Where method like this:

IObservableCollection<Product> products = new ObservableCollection<Product>();

// Either use the Method Chain syntax
IObservableCollection<Product> availableProducts =
    models.Where(product => product.NbAvailable > 0);

// Or the SQL-like syntax
IObservableCollection<Product> availableProducts =
    from product in products
    where product.NbAvailable > 0
    select product;

Last edited May 19, 2013 at 11:41 PM by Zumten, version 5

Comments

No comments yet.