I have an ObservableCollection Bound to a WPF List View. I am looking to be able to sort the columns of the ListView control by clicking on the Column Header. To do this I am sorting the ObservableCollection and letting the binding take care of updating the GUI.
To sort the ObservableCollection I am using the following code:
sortedData = new ObservableCollection<Tag>( from x in data
orderby x.ID descending
select x );
data = sortedData;
NB: data is bound to the ListView
The problem I'm having is that for each of the columns there would be a lot of copy-paste code to achieve the desired effect. Is it possible to pass the 'orderby x.ID descending' portion of the LINQ statement as a function parameter?
Or is there an entirely easier way to achieve the desired result?
You could use a Func as a method parameter containing a lambda expression.
If you want to order every single type by it's ID you could specify an interface on all of those types too and use a generic method.
For example
public ObservableCollection<Tag> Sort(Func<ObservableCollection<Tag>> sortFunc)
{
//do something else
data = sortFunc();
//do something else
}
which can be called like
Sort(list.OrderByDescending(x => x.ID));
in which list is your ObservableCollection.