using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; namespace SharpDevelop.XamlDesigner.PropertyGrid { /// /// Extends ObservableCollection{T} with an AddSorted method to insert items in a sorted collection. /// public class SortedObservableCollection : ObservableCollection { /// /// Creates a new SortedObservableCollection instance. /// /// The function to select the sorting key. public SortedObservableCollection(Func keySelector) { this.keySelector = keySelector; this.comparer = Comparer.Default; } Func keySelector; IComparer comparer; /// /// Adds an item to a sorted collection. /// public void AddSorted(T item) { int i = 0; int j = Count - 1; while (i <= j) { int n = (i + j) / 2; int c = comparer.Compare(keySelector(item), keySelector(this[n])); if (c == 0) { i = n; break; } if (c > 0) i = n + 1; else j = n - 1; } Insert(i, item); } } }