Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用c将数据表中的字符串项排序为int#_C#_Sorting - Fatal编程技术网

C# 使用c将数据表中的字符串项排序为int#

C# 使用c将数据表中的字符串项排序为int#,c#,sorting,C#,Sorting,我在数据表中存储了一些数字代码。当我尝试使用DataView对其进行排序时,它会按字符串对列进行排序。将数据排序为整数/数字的最简单方法是什么 DataView view = dt.DefaultView(); view.Sort = "Code asc"; dt = view.ToTable(); 数据表中的数据: 12812311212126 排序后显示: 112、12、123、126、128 预期结果: 在数据表中创建列时,将其定义为typeof(int) 下面是一个工作示例。您可以通过

我在数据表中存储了一些数字代码。当我尝试使用DataView对其进行排序时,它会按字符串对列进行排序。将数据排序为整数/数字的最简单方法是什么

DataView view = dt.DefaultView();
view.Sort = "Code asc";
dt = view.ToTable();
数据表中的数据: 12812311212126

排序后显示: 112、12、123、126、128

预期结果:
在数据表中创建列时,将其定义为typeof(int)


下面是一个工作示例。您可以通过Clone创建另一个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";

一个选项是添加具有正确类型的计算列并对其进行排序

像这样:

dt.Columns.Add( "Int32_Code", typeof( int ), "Code" );
dt.DefaultView.Sort("Int32_Code");
dt = dt.DefaultView.ToTable();

嗯,在我的代码中,我调用了返回数据表的Web服务,我只需执行
datatable dt=soaRequest.GetMasterList()
。尝试此dt.Columns[“code”]。DataType=Type.GetType(“System.Int32”);如果代码是“001”,数据类型从字符串变为整数会忽略前导零吗?
dt.Columns.Add( "Int32_Code", typeof( int ), "Code" );
dt.DefaultView.Sort("Int32_Code");
dt = dt.DefaultView.ToTable();