好吧,我剛剛颳起這件事真正的快,並沒有完成所有的neccessary錯誤處理和零檢查,但它應該給你一個想法,應該是enou GH讓你開始:
public static class DataTableExtensions
{
public static DataView ApplySort(this DataTable table, Comparison<DataRow> comparison)
{
DataTable clone = table.Clone();
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
rows.Sort(comparison);
foreach (DataRow row in rows)
{
clone.Rows.Add(row.ItemArray);
}
return clone.DefaultView;
}
}
用法:
DataTable table = new DataTable();
table.Columns.Add("IntValue", typeof(int));
table.Columns.Add("StringValue");
table.Rows.Add(11, "Eleven");
table.Rows.Add(14, "Fourteen");
table.Rows.Add(10, "Ten");
table.Rows.Add(12, "Twelve");
table.Rows.Add(13, "Thirteen");
//排序的StringValue:
DataView sorted = table.ApplySort((r, r2) =>
{
return ((string)r["StringValue"]).CompareTo(((string)r2["StringValue"]));
});
結果:
11十一
14十四
10十
13十三
12十二
//排序INTVALUE:
DataView sorted = table.ApplySort((r, r2) =>
{
return ((int)r["IntValue"]).CompareTo(((int)r2["IntValue"]));
});
結果:
10十
11十一
13十三
12十二
14十四
編輯:它更改爲擴展方法。
現在在你的Lambda中(或者你可以創建一個完整的比較方法),你可以做任何你需要的自定義排序邏輯。請記住,-1小於,0等於,1大於。
我欠你一杯啤酒。 – Orestes 2013-02-20 14:50:30
很好的回答。只需要對雙向排序進行一些調整,然後將視圖重新綁定到網格中。 – tys 2015-04-07 07:31:35