You can implement this behaviour yourself quite easily using the internal Move
method by extending the ObservableCollection<T>
class. Here is a simplified example:
public class SortableObservableCollection<T> : ObservableCollection<T>
{
public SortableObservableCollection(IEnumerable<T> collection) :
base(collection) { }
public SortableObservableCollection() : base() { }
public void Sort<TKey>(Func<T, TKey> keySelector)
{
Sort(Items.OrderBy(keySelector));
}
public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
{
Sort(Items.OrderBy(keySelector, comparer));
}
public void SortDescending<TKey>(Func<T, TKey> keySelector)
{
Sort(Items.OrderByDescending(keySelector));
}
public void SortDescending<TKey>(Func<T, TKey> keySelector,
IComparer<TKey> comparer)
{
Sort(Items.OrderByDescending(keySelector, comparer));
}
public void Sort(IEnumerable<T> sortedItems)
{
List<T> sortedItemsList = sortedItems.ToList();
for (int i = 0; i < sortedItemsList.Count; i++)
{
Items[i] = sortedItemsList[i];
}
}
}
Thanks to @ThomasLevesque for the more efficient Sort
method shown above
You can then use it like this:
YourCollection.Sort(c => c.PropertyToSortBy);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…