以编程方式排序我的SortableBindingList

时间:2015-01-26 21:49:59

标签: c# sorting bindinglist

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

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

1 个答案:

答案 0 :(得分:0)

如果我正确理解了引用,答案是你不能,你必须实现二级排序方法。所以我做到了。

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

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

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