使用c#将数据表中的字符串项目排序为int(Sort string items in a datatable as int using c#)

编程入门 行业动态 更新时间:2024-10-25 22:33:58
使用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";

更多推荐

本文发布于:2023-08-05 21:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1438373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数据表   项目   int   datatable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!