Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an observable collection?

I have a following class :

[DataContract] public class Pair<TKey, TValue> : INotifyPropertyChanged, IDisposable {     public Pair(TKey key, TValue value)     {         Key = key;         Value = value;     }      #region Properties     [DataMember]     public TKey Key     {         get         { return m_key; }         set         {             m_key = value;             OnPropertyChanged("Key");         }     }     [DataMember]     public TValue Value     {         get { return m_value; }         set         {             m_value = value;             OnPropertyChanged("Value");         }     }     #endregion      #region Fields     private TKey m_key;     private TValue m_value;     #endregion      #region INotifyPropertyChanged Members      public event PropertyChangedEventHandler PropertyChanged;      protected void OnPropertyChanged(string name)     {         PropertyChangedEventHandler handler = PropertyChanged;         if (handler != null)         {             handler(this, new PropertyChangedEventArgs(name));         }     }      #endregion      #region IDisposable Members      public void Dispose()     { }      #endregion } 

Which I've put in an ObservableCollection :

ObservableCollection<Pair<ushort, string>> my_collection =      new ObservableCollection<Pair<ushort, string>>();  my_collection.Add(new Pair(7, "aaa")); my_collection.Add(new Pair(3, "xey")); my_collection.Add(new Pair(6, "fty")); 

Q : How do I sort it by key ?

like image 403
Maciek Avatar asked Dec 22 '09 10:12

Maciek


People also ask

Is ObservableCollection sorted?

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.

What are observable collections?

An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated.

How do you sort a list in C#?

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.


2 Answers

This simple extension worked beautifully for me. I just had to make sure that MyObject was IComparable. When the sort method is called on the observable collection of MyObjects, the CompareTo method on MyObject is called, which calls my Logical Sort method. While it doesn't have all the bells and whistles of the rest of the answers posted here, it's exactly what I needed.

static class Extensions {     public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable     {         List<T> sorted = collection.OrderBy(x => x).ToList();         for (int i = 0; i < sorted.Count(); i++)             collection.Move(collection.IndexOf(sorted[i]), i);     } }  public class MyObject: IComparable {     public int CompareTo(object o)     {         MyObject a = this;         MyObject b = (MyObject)o;         return Utils.LogicalStringCompare(a.Title, b.Title);     }      public string Title;  }   .   .   . myCollection = new ObservableCollection<MyObject>(); //add stuff to collection myCollection.Sort(); 
like image 63
NielW Avatar answered Sep 17 '22 19:09

NielW


I found a relevant blog entry that provides a better answer than the ones here:

http://kiwigis.blogspot.com/2010/03/how-to-sort-obversablecollection.html

UPDATE

The ObservableSortedList that @romkyns points out in the comments automatically maintains sort order.

Implements an observable collection which maintains its items in sorted order. In particular, changes to item properties that result in order changes are handled correctly.

However note also the remark

May be buggy due to the comparative complexity of the interface involved and its relatively poor documentation (see https://stackoverflow.com/a/5883947/33080).

like image 44
Eric J. Avatar answered Sep 21 '22 19:09

Eric J.