我正在尝试编写一个可用于我的应用程序的 SortableBindingList。我发现了很多关于如何实现基本排序支持的讨论,以便 BindingList 在 DataGridView 或其他一些绑定控件的上下文中使用时进行排序,包括来自 StackOverflow 的这篇文章:
DataGridView sort and eg BindingList<T> in .NET
这一切都非常有帮助,我已经实现了代码、测试等,并且一切正常,但在我的特定情况下,我需要能够支持对 Sort() 的简单调用,并让该调用使用默认的 IComparable。 CompareTo() 进行排序,而不是调用 ApplySortCore(PropertyDescriptor, ListSortDirection)。
原因是因为我有相当多的代码依赖于 Sort() 调用,因为这个特定的类最初继承自 List,最近被更改为 BindingList。
具体来说,我有一个名为 VariableCode 的类和一个名为 VariableCodeList 的集合类。VariableCode 实现了 IComparable 并且其中的逻辑基于几个属性等而适度复杂......
public class VariableCode : ... IComparable ...
{
public int CompareTo(object p_Target)
{
int output = 0;
//some interesting stuff here
return output;
}
}
public class VariableCodeList : SortableBindingList<VariableCode>
{
public void Sort()
{
//This is where I need help
// How do I sort this list using the IComparable
// logic from the class above?
}
}
我在 Sort() 中重新利用 ApplySortCore 方法进行了几次失败的尝试,但一直阻碍我的是 ApplySortCore 期望 PropertyDescriptor 进行排序,我不知道如何让它使用 IComparable .CompareTo() 逻辑。
有人可以指出我正确的方向吗?
非常感谢。
编辑:这是基于 Marc 的响应的最终代码,以供将来参考。
/// <summary>
/// Sorts using the default IComparer of T
/// </summary>
public void Sort()
{
sort(null, null);
}
public void Sort(IComparer<T> p_Comparer)
{
sort(p_Comparer, null);
}
public void Sort(Comparison<T> p_Comparison)
{
sort(null, p_Comparison);
}
private void sort(IComparer<T> p_Comparer, Comparison<T> p_Comparison)
{
m_SortProperty = null;
m_SortDirection = ListSortDirection.Ascending;
//Extract items and sort separately
List<T> sortList = new List<T>();
this.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 = RaiseListChangedEvents;
RaiseListChangedEvents = false;
try
{
ClearItems();
sortList.ForEach(item => this.Add(item));
}
finally
{
RaiseListChangedEvents = oldRaise;
ResetBindings();
}
}