How can I sort an ObservableCollection <T> so that my interface also sees the sorting process?

I have a Listbox whose toolbar is set to wrappanel. I want that whenever a new item is added to the list, my collection should be sorted, and the process should be visible in the user interface. I mean, the user should be able to see this spectacular effect to help them determine that the item is being sorted. I looked at some posts in stackoverflow and they suggest using CollectionViewSource. However, my itemsource is bound to an ObservableCollection in the ViewModel.

I wrote this code first. It works, however, since the new collection is tied, I do not see this unusual effect when items in the container simply move to a new position from the starting position: -

 var photoList = PhotosToUpload.ToList<Photo>();
            photoList.Sort(new PhotoSorter());
            PhotosToUpload = new ObservableCollection<Photo>(photoList);

This is my class: -

 public class PhotoSorter : IComparer<Photo>
    {

        public int Compare(Photo x, Photo y)
        {
            return x.PhotoByteArr.Length - x.PhotoByteArr.Length;
        }
    }

Then I wrote a simple bubble sorting algorithm. This gives the desired effect, but I do not know why it takes too much time. I know that this is the most inefficient algorithm that everyone can think of, but still sorting 10 items should not take more than a second. Here it takes 4-5 seconds.

for (int i = 0; i < PhotosToUpload.Count; i++)
            {
                for (int j = 0; j < PhotosToUpload.Count - 1 - i; j++)
                {
                    if (PhotosToUpload[j].PhotoByteArr.Length > PhotosToUpload[j + 1].PhotoByteArr.Length)
                    {
                        Photo photo = PhotosToUpload[j];
                        PhotosToUpload[j] = PhotosToUpload[j + 1];
                        PhotosToUpload[j + 1] = photo;
                    }
                }
            }

Can someone tell me what I can do at this moment? and why does sorting the bubbles take so long even with only 10 items?

+3
source share
1 answer

, CollectionChanged.

:

return x.PhotoByteArr.Length - y.PhotoByteArr.Length;

. ... , Photo? /?

Photo.PhotoByteArr ?

+1

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


All Articles