I have below ObservableCollection<string>
. I need to sort this alphabetically.
private ObservableCollection<string> _animals = new ObservableCollection<string> { "Cat", "Dog", "Bear", "Lion", "Mouse", "Horse", "Rat", "Elephant", "Kangaroo", "Lizard", "Snake", "Frog", "Fish", "Butterfly", "Human", "Cow", "Bumble Bee" };
I tried _animals.OrderByDescending
. But I don't know how to use it correctly.
_animals.OrderByDescending(a => a.<what_is_here_?>);
How can I do this?
This is an ObservableCollection<T> , that automatically sorts itself upon a change, triggers a sort only when necessary, and only triggers a single move collection change action. Descending seems to be implemented reverse.
Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
Basically, if there is a need to display a sorted collection, please consider using the CollectionViewSource
class: assign ("bind") its Source
property to the source collection — an instance of the ObservableCollection<T>
class.
The idea is that CollectionViewSource
class provides an instance of the CollectionView
class. This is kind of "projection" of the original (source) collection, but with applied sorting, filtering, etc.
References:
WPF 4.5 introduces "Live Shaping" feature for CollectionViewSource
.
References:
If there still a need to sort an instance of the ObservableCollection<T>
class, here is how it can be done. The ObservableCollection<T>
class itself does not have sort method. But, the collection could be re-created to have items sorted:
// Animals property setter must raise "property changed" event to notify binding clients. // See INotifyPropertyChanged interface for details. Animals = new ObservableCollection<string> { "Cat", "Dog", "Bear", "Lion", "Mouse", "Horse", "Rat", "Elephant", "Kangaroo", "Lizard", "Snake", "Frog", "Fish", "Butterfly", "Human", "Cow", "Bumble Bee" }; ... Animals = new ObservableCollection<string>(Animals.OrderBy(i => i));
Please note that OrderBy()
and OrderByDescending()
methods (as other LINQ–extension methods) do not modify the source collection! They instead create a new sequence (i.e. a new instance of the class that implements IEnumerable<T>
interface). Thus, it is necessary to re-create the collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With