Programming Stuff

Sort a Collection / ObservableCollection

I saw many interesting posting regarding to sort, but I found many constraints such as library/dll requirements (IEnumerable -> Move required System.dll v4.0 – no available in Silverlight), and other complications such as create copy of the object or used custom object (e.g. SortedObservableCollection).
Perhaps this solutions is not the most efficient, it’s really convenient for me and I hope for you too. Don’t required to change your current collection or create duplicates.
The main advantage is on binding. For example, if you have a collection binding to any of Silverlight controls, such as ItemsControl that doesn’t have any sorting method compare to a DataGrid (DataGrid Sorting doesn’t work for custom columns), this code will be very helpful.
Consider this Person Class:

You can sort using this way… but you’ll lose the binding. This is NOT good idea.

It’s better to use this sorting method (using Generic, delegate, linq):

and you can do something like this:

In this case, the collection still the same, so you’ll keep the binding.

Have a good day. God bless you!

Related Post