2015-01-26 22 views
0

我已經實現了一個排序綁定列表類:編程排序我SortableBindingList

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 
+0

https://social.msdn.microsoft.com/Forums/en -US/4c5202c9-f414-4b41-9c04-071d0c1af413/sort-bindinglist?forum = linqtosql || http://stackoverflow.com/questions/1063917/bindinglistt-sort-to-behave-like-a-listt-sort – MethodMan 2015-01-26 21:54:24

回答

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

然後在我的窗口小部件,我不得不實現一個比較器:

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