Earlier this week, I went looking for a way to filter Entity Collection classes. I ran across a good article, Sorting the Unsortable Collection by Rocky Lhotka that details a VB wrapper class allowing sorting of strongly-typed collections.
I liked the method that he presented, and created a
similar called CollectionView that adds a feature for filtering.
You can grab the class source for CollectionView here.
Using this class is easy. Say you want to bind your strongly
typed collection to a DataGrid, and enable sorting and filtering.
Simply pass your collection class to the constructor of the
CollectionView, and bind your grid to the CollectionView instance
instead.
CollectionView view = new CollectionView(MyCollectionClass);
this.DataGrid1.DataSource = view;
this.DataGrid1.DataBind();
Now, if you're using WinForms, you shouldn't have to do anything
else to get Sorting to work, but if you're using the ASP.NET DataGrid,
you have to wire up your Sort events. To actually do the sort,
use code like this:
view.ApplySort(e.SortExpression, System.ComponentModel.ListSortDirection.Ascending);
I
implemented some simple code for filtering, it's admittedly limited,
but it gets the job done for simple filters. You should be
able to expand this for multiple filters, by overloading the
ApplyFilter method to accept an ArrayList of filters or even better, a
strongly typed collection of filter objects or something like
that. But for simple filtering, with equals comparisons, just do
the following:
view.ApplyFilter("PropertyName", propertyComparison);
Where property comparison is the object to compare against.
There's an overload too for NotEquals comparisons. Anyhow hope
this will simplify some aspects of DataBinding strongly typed
collections for you.
-Brendan