Reputation: 4570
Hi I have an ObservableCollection
in which where I add an item, I want to sort it.
I want to sort it on a key so for example:
collection.OrderByDescending(x => x.property)
I have created an extension method that will sort when the item is added too (.Add
), however, the extension method needs to do something like the above code. Using the code from the extension method below, can someone help me?
public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable
{
List<T> sorted = collection.OrderByDescending(x => x).ToList();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
Also does the generic really need to implement the IComparable
interface? (I am very new to extension methods).
Upvotes: 2
Views: 1356
Reputation: 3168
This is working for me:
ConceptItems = new ObservableCollection<DataConcept>(ConceptItems.OrderBy(i => i.DateColumn));
Upvotes: 1
Reputation: 292565
Typically, when you use an ObservableCollection<T>
, you don't sort it directly; instead, you apply a sort on the view of the collection (ICollectionView interface). If you bind your UI directly to the ObservableCollection<T>
, you can apply a sort like this:
var view = CollectionViewSource.GetDefaultView(collection);
view.SortDescriptions.Add(new SortDescription("MyProperty", ListSortDirection.Descending));
You only need to do it once; if you add or remove items, the collection view will automatically re-sort itself. It also works if you change the value of MyProperty
, provided that T
implements INotifyPropertyChanged
.
See also: How to: Get the Default View of a Data Collection
(I'm assuming that you're writing a WPF application; this approach won't work for Windows Phone or Windows Store apps)
Upvotes: 2