Search code examples
c#wpfsortingcollectionviewcollectionviewsource

How to get the source collection of ICollectionView preserving the sort order?


In my WPF application, I have an ICollectionView that I use to display a list of data in a data grid after filtering and sorting. Once I do the filtering and sorting the way I like, I would like to export the source collection preserving the sort order.

I can get my underlying source collection after filtering like so:

var items = CollectionViewSource.GetDefaultView(MyICollectionView).SourceCollection.Cast<MyItemType>();

This returns my filtered items just fine, but it loses the sorted order. How do I get the filtered list preserving the order as well?

I know I can get the sort descriptions like below:

var sortDescriptions = CollectionViewSource.GetDefaultView(MyICollectionView).SortDescriptions;

But that merely returns the sort properties in string format, which won't help me in my case.


Solution

  • CollectionViewSource.GetDefaultView(Control.ItemsSource);
    

    Control here is the itemscontrol that you bound the collection "MyICollectionView" to. For more information check out how-to-get-the-default-view-of-a-data-collection