0

これは私が現在ソートを行っている方法です:

 BindingSource bs = ( BindingSource )m_dataGrid.DataSource;
bs.Sort = "SortingRow" + " DESC";

私が欲しいのは、カスタムメソッドまたは私がソートに使用するものです。

bool GreaterThan(object a, object b)
{
(...)//my own code to determine return value
}

どうすればこれを達成できますか?

4

1 に答える 1

1

それを行う方法はたくさんあります。

通常、DataSource オブジェクトは、DataTable、DataView、または最初のオブジェクトにキャストバックできます。

あなたのプロジェクトがわからないので、DataTable を使用します。

データが追加されたら、DataTable にキャストし直します。

private void AddData(object data) {
  // data would be what you would normally fill to the m_dataGrid.DataSource
  DataTable table = m_dataGrid.DataSource as DataTable;
  if (table == null) {
    DataView view = m_dataGrid.DataSource as DataView;
    if (view != null) {
      table = view.Table;
    }
  }
  if (table != null) {
    Sort(table);
  }
}

既知のデータをルーチンに渡す方法AddDataが必要なだけなので、見た目は関係ありません。Sort

あなたのSortルーチンはあなたが書くものである必要があります。生データを構造化データ型に戻します。ここではジェネリックMyStuffクラスとして示しています。

private void Sort(DataTable table) {
  List<MyStuff> list = new List<MyStuff>(table.Rows.Count);
  for (int i = 0; i < table.Rows.Count; i++) {
    string valueA = table.Rows[MyStuff.A_INDEX].ToString();
    int itemB = Convert.ToInt32(table.Rows[MyStuff.B_INDEX]);
    list.Add(new MyStuff() { ValueA = valueA, ItemB = itemB });
  }
  list.Sort();
  m_dataGrid.DataSource = list;
}

を機能させるには、クラスに インターフェイスとインターフェイスlist.Sort()を実装する必要があります。IComparableIEquatableMyStuff

アイデアを提供するためのくだらない一般的な例:

class MyStuff : IComparable<MyStuff>, IEquatable<MyStuff> {

  public const int A_INDEX = 0;
  public const int B_INDEX = 0;

  public MyStuff() {
    ValueA = null;
    ItemB = 0;
  }

  public string ValueA { get; set; }

  public int ItemB { get; set; }

  #region IComparable<MyStuff> Members

  public int CompareTo(MyStuff other) {
    if (other != null) {
      if (!String.IsNullOrEmpty(ValueA) && !String.IsNullOrEmpty(other.ValueA)) {
        int compare = ValueA.CompareTo(other.ValueA);
        if (compare == 0) {
          compare = ItemB.CompareTo(other.ItemB); // no null test for this
        }
        return compare;
      } else if (!String.IsNullOrEmpty(other.ValueA)) {
        return -1;
      }
    }
    return 1;
  }

  #endregion

  #region IEquatable<MyStuff> Members

  public bool Equals(MyStuff other) {
    int compare = CompareTo(other);
    return (compare == 0);
  }

  #endregion

}

それが役立つことを願っています。

しかし、今日締め切りがあるので、これ以上これ以上時間を費やすことはできません.

〜ジョー

于 2013-01-08T14:45:27.347 に答える