简体   繁体   中英

Programmatically sorting my SortableBindingList

I have a class that implements a sortable binding list:

public class MySortableBindingList_C<T> : BindingList<T>, IBindingListView, IBindingList, IList, ICollection, IEnumerable

It works just fine in a data grid view, this successfully sorts the list:

    public Form1(MySortableBindingList_C<Widget_C> sortable)
    {
        InitializeComponent();
        dataGridView1.DataSource = sortable;
        dataGridView1.Sort(dataGridView1.Columns["Id"], ListSortDirection.Ascending);
        this.Close();
    }

But how do I sort that without the use of DataGridView?

Things I have tried:

MySortableBindingList_C<Widget_C> sortable = new MySortableBindingList_C<Widget_C>();
sortable.Add(new Widget_C { Id = 5, Name = "Five" });
sortable.Add(new Widget_C { Id = 3, Name = "Three" });
sortable.Add(new Widget_C { Id = 2, Name = "Two" });
sortable.Add(new Widget_C { Id = 4, Name = "Four" });
sortable.OrderBy(w=> w.Id); // sorts, but produces a new sorted result, does not sort original list
sortable.ApplySort(new ListSortDescriptionCollection({ new ListSortDescription(new PropertyDescriptor(), ListSortDirection.Ascending)));  // PropertyDescriptor is abstract, does not compile
typeof(Widget_C).GetProperty("Id"); // This gets a PropertyInfo, not a PropertyDescriptor

If I'm understanding the references correctly, the answer is you can't, you have to implement a secondary sort method. So I did.

Implementation was fairly straightforward given MySortableBindingList inherits from BindingList.

    public void Sort(Comparison<T> comparison)
    {
        List<T> itemsList = (List<T>)this.Items;
        itemsList.Sort(comparison);
        this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
    }

Then in my Widget I had to implement a comparer:

    public static int CompareById(Widget_C x, Widget_C y)
    {
        if (x == null || y == null) // null check up front
        {
            // minor performance hit in doing null checks multiple times, but code is much more 
            // readable and null values should be a rare outside case.
            if (x == null && y == null) { return 0; } // both null
            else if (x == null) { return -1; } // only x is null
            else { return 1; } // only y is null
        }
        else { return x.Id.CompareTo(y.Id); }
    }

And call thusly:

        sortable.Sort(Widget_C.CompareById);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM