以编程方式对我的 SortableBindingList 进行排序

Programmatically sorting my SortableBindingList

我有一个 class 实现了一个可排序的绑定列表:

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

它在数据网格视图中工作得很好,这成功地对列表进行了排序:

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

但是我如何在不使用 DataGridView 的情况下对其进行排序?

我尝试过的事情:

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

如果我对引用的理解正确,那么答案是你不能,你必须实现辅助排序方法。所以我做到了。

鉴于 MySortableBindingList 继承自 BindingList,实现相当简单。

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

然后在我的小部件中我必须实现一个比较器:

    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); }
    }

并这样称呼:

        sortable.Sort(Widget_C.CompareById);