好的,我只是快速地提出了建议,并没有进行所有必要的错误处理和null检查,但是它应该给您一个想法,并且应该足以使您入门:
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点11分
14十四
10十
13十三
12十二
//按IntValue排序:
DataView sorted = table.ApplySort((r, r2) => { return ((int)r["IntValue"]).CompareTo(((int)r2["IntValue"])); });结果:
10十
11点11分
13十三
12十二
14十四
编辑:更改为扩展方法。
现在,在Lambda中(或您可以创建完整的比较方法),您可以执行所需的任何类型的自定义排序逻辑。请记住,-1小于,0等于,1大于。



