Sort ObservableCollection - what is the best approach?
ICollectionView
seems to be a perfect fit for this. It was designed specifically for sorting, filtering and grouping of a collection without modifying the original collection.
You can get an instance of ICollectionView
for your collection using the following code:
var sortedCities = CollectionViewSource.GetDefaultView(City);
Then you can setup sorting by adding instances of SortDescription
type to the ICollectionView.SortDescriptions
collection:
sortedCities.SortDescriptions.Add(new SortDescription("IsSelected", ListSortDirection.Descending));sortedCities.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
Then you can bind your ComboBox
directly to the collection view (instead of City
collection) and it will display already sorted data.