ListCollectionView for sorting,filtering data collection

When we wanted to perform filtering, sorting of data over a binded data collection, collection view might be helpful. If the source collection implements INotifyCollectionChanged interface, the changes raised by the CollectionChanged event are reflected to the views.

ListcollectionView Represents the collection view for collections that implement IList as Mictosoft Doc says.

Create a collection view

In order to use ListCollectionView you have to use ObjectModel

using System.Collections.ObjectModel;

Then you can use any list to create ListCollectionView, in this example I used my observable collection of SalesOrder.

ListCollectionView sorderview = null;
collectionview = new ListCollectionView(salesOrderCollection);

Model View Class

class SalesOrderView
    {   public DateTime Date { get; set; }
        public string Customer{ get; set; }        
        public string Amount{ get; set; }

Create a Custom filter

Let’s play with filter, first up all we need to create some custom filter for searching SalesOrders received from customers on a specific date

collectionview.Filter = (e1) =>
                    SaleOrderView sorder = e1 as SaleOrderView ;
                    if (((Convert.ToDateTime(sorder.Date) >= dtp_from.SelectedDate && 
Convert.ToDateTime(sorder.Date) <= dtp_to.SelectedDate)) )
                        return true;
                    return false;

That is it, now you can simply bind the collection view with DataGrid or Listcontrol. For me it is a Grid

 mydatagrid.ItemsSource = collectionview;

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.