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

前端 未结 2 764
南笙
南笙 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 14:48

    I had the same problem and this post helped me solve it!

    As I implemented this solution (based on Marc's and Paul's code) as an extension and added two simple sort methods, I would like to share it with you:

    public static void SortAscending(this BindingList bindingList, Func sortProperty)
        {
            bindingList.Sort(null, (a, b) => ((IComparable

    )sortProperty(a)).CompareTo(sortProperty(b))); } public static void SortDescending(this BindingList bindingList, Func sortProperty) { bindingList.Sort(null, (a, b) => ((IComparable

    )sortProperty(b)).CompareTo(sortProperty(a))); } public static void Sort(this BindingList bindingList) { bindingList.Sort(null, null); } public static void Sort(this BindingList bindingList, IComparer comparer) { bindingList.Sort(comparer, null); } public static void Sort(this BindingList bindingList, Comparison comparison) { bindingList.Sort(null, comparison); } private static void Sort(this BindingList bindingList, IComparer p_Comparer, Comparison p_Comparison) { //Extract items and sort separately List sortList = new List(); bindingList.ForEach(item => sortList.Add(item));//Extension method for this call if (p_Comparison == null) { sortList.Sort(p_Comparer); }//if else { sortList.Sort(p_Comparison); }//else //Disable notifications, rebuild, and re-enable notifications bool oldRaise = bindingList.RaiseListChangedEvents; bindingList.RaiseListChangedEvents = false; try { bindingList.Clear(); sortList.ForEach(item => bindingList.Add(item)); } finally { bindingList.RaiseListChangedEvents = oldRaise; bindingList.ResetBindings(); } } public static void ForEach(this IEnumerable source, Action action) { if (source == null) throw new ArgumentNullException("source"); if (action == null) throw new ArgumentNullException("action"); foreach (T item in source) { action(item); } }

    Hope this is helpful.

提交回复
热议问题