好吧,我刚刚刮起这件事真正的快,并没有完成所有的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