I am working with WPF and encountered a problem about sorting in a List.
I find the sample that it use OrderBy( T => T.[the field that refer to it for sorting])
e.g.
List<Contact> contacts = new List<Contact>();
contacts.OrderBy(Contact => Contact.PhoneNumber)
It works perfectly.
However, if I don’t know the type and even don’t know the field in that type, how should I implement the sorting function?
Like: what should I put in in OrderBy(??? => ????.?????)
In fact, I wanna make a general GridView in which, when user click on one of the header, it will sort the whole list by the corresponding column.
Thank you so much!
Two solutions for dynamic sorting …
GridView’s ItemsSource is set to a
ICollectionVieworListCollectionViewwithSourceCollectionset as your own List and having aSortDescriptionwhere PropertyName can be specified as a string value… http://marlongrech.wordpress.com/2008/11/22/icollectionview-explained/Dynamic LINQ with
MyList.AsQueryable().OrderBy(<OrderByClause>)where order by clause can be created dynamically… How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?So when user clicks on the grid view column headers, you have to extract the property name that the column is representing and use any of the two above approaches. In option 2 you would have to set the ItemsSource after the collection is sorted.
Any of the two approaches can be done in an Attached Behavior that works on GridViews in order to have a generic solution.
OR
All you have to worry about it if you use option1, then you would have to assume that the GridView.ItemsSource is always going to be an ICollectionView. In second approach the trade off is you would have to “set” the ItemsSource after sorting.
I hope this helps…