BindingList.Sort() to behave like a List.Sort()

前端 未结 2 767
南笙
南笙 2020-12-01 13:59

I am attempting to write a SortableBindingList that I can use for my application. I have found lots of discussion about how to implement basic sorting support so that the B

2条回答
  •  我在风中等你
    2020-12-01 15:02

    Emulating a property just to do the sort is probably overkill. The first thing to look at is Comparer.Default. It might, however, turn out that the easiest thing to do is to:

    • extract the data into List or similar
    • sort the extracted data
    • disable notifications
    • reload the data
    • re-enable notifications
    • send a "reset" message

    btw, you should be disabling notifications during your existing sort, too.

    public void Sort() {
        // TODO: clear your "sort" variables (prop/order)
    
        T[] arr = new T[Count];
        CopyTo(arr, 0);
        Array.Sort(arr);
        bool oldRaise = RaiseListChangedEvents;
        RaiseListChangedEvents = false; // <=== oops, added!
        try {
            ClearItems();
            foreach (T item in arr) {
                Add(item);
            }
        } finally {
            RaiseListChangedEvents = oldRaise;
            ResetBindings();
        }    
    }
    

提交回复
热议问题