アプリケーションに使用できる SortableBindingList を作成しようとしています。基本的な並べ替えサポートを実装する方法について多くの議論を見つけたので、DataGridView または StackOverflow からのこの投稿を含む他のバインドされたコントロールのコンテキストで使用されたときに BindingList が並べ替え
られます。
これはすべて非常に役に立ち、コードを実装してテストなどを行い、すべて機能していますが、私の特定の状況では、Sort() への単純な呼び出しをサポートし、その呼び出しでデフォルトの IComparable を使用できるようにする必要があります。 ApplySortCore(PropertyDescriptor, ListSortDirection) を呼び出すのではなく、CompareTo() で並べ替えを行います。
その理由は、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();
}
}