ObservableCollection Grouping

Collection: GroupByObservatorCollection<TKey, T>
Extension methods:
  • ObservatorCollectionExtensions.GroupBy(source, keySelector)
  • ObservatorCollectionExtensions.GroupBy(source, keySelector, keyComparer)


This collection listens to an IObservableCollection<T> to build a new observable collection group all the elements into different buckets, using the keySelector and the keyComparer.


The following example shows how to create a collection of requests that will be grouped by their StatusCode. The property StatusCode is expected to change during the processing, and the GroupByObservableCollection is supposed to keep track of all the changes.

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

public class Employee : INotifyPropertyChanged
    public Employee(string name, string department)
        _department = department;
        Name = name;

    public string Name { get; private set; }

    private string _department;
    public string Department
        get { return _department; }
            if (_department != value)
                _department = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Department"));

    public event PropertyChangedEventHandler PropertyChanged;

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

IObservableCollection<Employee> employees = new ObservableCollection<Employee>();

// Either use the Method Chain syntax
var employeesByDepartment =
    employees.GroupBy(x => x.Department);

// Or the SQL-like syntax
var employeesByDepartment =
    from employee in employees
    group employee by employee.Department into grp
    select grp;

// Add some random employees
employees.Add(new Employee("Flora Kingman", "Marketing"));
employees.Add(new Employee("Carletta Huffaker", "Marketing"));
employees.Add(new Employee("Allison Baisden", "Sales"));
employees.Add(new Employee("Phuong Matte", "Human resources"));
employees.Add(new Employee("Darci Tittle", "Human resources"));

// Flora moved to the Sales department. She changes group automatically
employees[0].Department = "Sales";

// Carletta moved from Marketing to Human resources. The Marketing group is automatically removed.
employees[1].Department = "Human resources";

Last edited May 19, 2013 at 11:42 PM by Zumten, version 4


No comments yet.