ObservableCollection Sorting

Collection: SortObservatorCollection<T>
Extension methods:
  • ObservatorCollectionExtensions.Sort(source, comparer)
  • ObservatorCollectionExtensions.OrderBy(source, keySelector, keyComparer)
  • ObservatorCollectionExtensions.OrderByDescending(source, keySelector, keyComparer)
  • ObservatorCollectionExtensions.ThenBy(sortCollection, keySelector, keyComparer)
  • ObservatorCollectionExtensions.ThenByDescending(sortCollection, keySelector, keyComparer)


This collection listens to an IObservableCollection<T> to build a new one sorting all of it's items, sorting them using a comparer.


The following example shows how to sort a list of products by their price, then by their name

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

public class Product : INotifyPropertyChanged
    public Product(string name, decimal price)
        _price = price;
        Name = name;

    public string Name { get; private set; }

    private decimal _price;
    public decimal Price
        get { return _price; }
            if (_price != value)
                _price = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Price"));

    public event PropertyChangedEventHandler PropertyChanged;

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

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

// Either use the Method Chain syntax
IObservableCollection<Product> productsByPrice = products
    .OrderBy(x => x.Price)
    .ThenBy(x => x.Name);

// Or the SQL-like syntax
IObservableCollection<Product> productsByPrice =
    from product in products
    orderby product.Price, product.Name
    select product;

// Display it on a ListView
lstProducts.ItemsSource = productsByPrice;

// Insert random products
products.Add(new Product("Candle", 1m));
products.Add(new Product("Baseball bat", 10m));
products.Add(new Product("T-shirt", 9.99m));
products.Add(new Product("Soap", 2m));

// If you update the price, the order will be automatically updated.
products[2].Price = 11m;

Last edited Jun 2, 2013 at 5:21 PM by Zumten, version 5


No comments yet.