使用c#将数据表中的字符串项目排序为int(Sort string items in a datatable as int using c#)
我有一些数字代码存储在DataTable中。 当我尝试使用DataView对它进行排序时,它按字符串对列进行排序。 将数据按整数/数字排序的最简单方法是什么?
DataView view = dt.DefaultView(); view.Sort = "Code asc"; dt = view.ToTable();数据表中的数据:128,123,112,12,126
排序后显示:112,12,123,126,128
预期成果:12,112,123,126,128
I have some numeric codes stored in a DataTable. When I try to sort it using DataView it sorts the column by string. What is the easiest way to sort the data as integer/number?
DataView view = dt.DefaultView(); view.Sort = "Code asc"; dt = view.ToTable();Data in datatable: 128, 123, 112, 12, 126
after sort it shows: 112, 12, 123, 126, 128
expected result: 12, 112, 123, 126, 128
最满意答案
这是一个工作示例。 您可以通过克隆创建另一个DataTable,并将列的数据类型更改为Int并复制数据。
DataTable dt = GetTable(); // Assume this method returns the datatable from service DataTable dt2 = dt.Clone(); dt2.Columns["Code"].DataType = Type.GetType("System.Int32"); foreach (DataRow dr in dt.Rows) { dt2.ImportRow(dr); } dt2.AcceptChanges(); DataView dv = dt2.DefaultView; dv.Sort = "Code ASC";Here is working example. You can create another DataTable via Clone, and change the data type of the column to Int and copy the data.
DataTable dt = GetTable(); // Assume this method returns the datatable from service DataTable dt2 = dt.Clone(); dt2.Columns["Code"].DataType = Type.GetType("System.Int32"); foreach (DataRow dr in dt.Rows) { dt2.ImportRow(dr); } dt2.AcceptChanges(); DataView dv = dt2.DefaultView; dv.Sort = "Code ASC";更多推荐
发布评论