Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ObservableCollection - what is the best approach?

Tags:

mvvm

wpf

I have a ObservableCollection , where MyData is a class with 4 properties i.e. int id, string name, bool IsSelected, string IsVisible.

This ObservableCollection is binded to a combobox with checkboxes(Cities data for example). Now, when the user checks the checkboxes then next time when he opens the drop down - all selections should come on top in ascending order by name.

I have also implemented auto complete when the user types in 3 chars in the combobox, the drop down will open showing all the selections first, then then all the items starting from the 3 chars type in by the user.

I have researched and implemented the following code and it is working fine, but i want to know whether this is the best approach or can i implement this in a better manner, code is :

        IEnumerable<MyData> sort;
        ObservableCollection<MyData> tempSortedCities = new ObservableCollection<MyData>();
        sort = City.OrderByDescending(item => item.IsSelected).ThenBy(item => item.Name.ToUpper()) ; 
       // City is my observablecollection<MyData> property in my Model binded to combobox in UI
        foreach (var item in sort)
            tempSortedCities.Add(item);


        City.Clear(); // City is my observablecollection<MyData> property in my Model
        City = tempSortedCities;
        tempSortedCities = null;
        sort = null;  

Thanks in advance for your time !

like image 484
Gurpreet Singh Avatar asked Apr 12 '11 06:04

Gurpreet Singh


1 Answers

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.

like image 53
Pavlo Glazkov Avatar answered Nov 16 '22 01:11

Pavlo Glazkov