Sort list versus observed set

I found out that I am “doing WPF wrong” and it is frustrating to redo a lot of code.

How could I convert the following:

public static class SortName { public static int Compare(Person a, Person b) { return a.Name.CompareTo(b.Name); } } 

and I call it like this:

 list.Sort(SortName.Compare); 

into the format needed for the ObservableCollection. And as I would call it. So far I have tried this, based on what I read here

 class ObservableCollectionSortName<T> : ObservableCollection<T> { public int Compare (Person a, Person b) { return a.Name.CompareTo(b.Name); } } 
+4
source share
2 answers

The observed collection does not sort for the simple reason that every time an item moves from one place in the list to another, the collection raises an event. It would be great to watch the animation of the sorting algorithm in action, but it kind of sucks, you know, sorting.

There are two ways to do this; they are very similar, and both begin by sorting items outside their observable collection, for example. if _Fruits is an ObservableCollection<Fruit> , and you defined IComparer<Fruit> to sort, you would do:

 var sorted = _Fruits.OrderBy(x => x, new FruitComparer()); 

This creates a new IEnumerable<Fruit> , which, when you iterate over it, will have objects in the new order. There are two things you can do with this.

One of them is to create a new collection, replace the old one and force the elements (elements) of elements in the user interface to reinstall on it:

 _Fruits = new ObservableCollection<Fruit>(sorted); OnPropertyChanged("Fruits"); 

(It is assumed that your class implements INotifyPropertyChanged usual way.)

Another is to create a new sorted list and then use it to move items in your collection:

 int i = 0; foreach (Fruit f in sorted) { _Fruits.MoveItem(_Fruits.IndexOf(f), i); i++; } 

The second approach is that I will only try if I had a really serious obligation not to reinstall the controls for the elements, because it collects a ton of events related to a collection change.

+14
source

If the main reason for sorting your observed collection is to display the data in the sorted list to the user, and not for performance reasons (for example, faster access), then you can use CollectionViewSource. Bea Stollnitz has a good description on her blog about how to use CollectionViewSource to implement sorting and grouping collections for the user interface .

This may help, as it means you don’t have to sort by your observed collection and worry about the performance hits Robert indicated for sending INotifyCollectionChanged. However, this will allow the elements to be displayed in sorted order in the user interface.

+3
source

Source: https://habr.com/ru/post/1302306/


All Articles