【问题标题】:Sort string items in a datatable as int using c#使用c#将数据表中的字符串项排序为int
【发布时间】:2011-11-26 05:25:01
【问题描述】:

我有一些数字代码存储在数据表中。当我尝试使用 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

【问题讨论】:

    标签: c# sorting


    【解决方案1】:

    这是工作示例。您可以通过 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";
    

    【讨论】:

    • 如果代码为“001”会发生什么,从字符串变为整数的数据类型会省略前导零吗?
    【解决方案2】:

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

    像这样:

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

    【讨论】:

      【解决方案3】:

      在数据表中创建列时,将其定义为 typeof(int)

      dt.Columns.Add("Code", typeof(int));
      

      【讨论】:

      • 嗯,在我的代码中,我调用了返回数据表的 web 服务,我只需执行 DataTable dt = soaRequest.GetMasterList();
      • 试试这个 dt.Columns["Code"].DataType = Type.GetType("System.Int32");
      【解决方案4】:

      在数据表中创建一个新列,如下所示,并在新列 code_int 上排序 Dt.Columns.Add("Code_int", typeof(Int16), "Convert(Code, 'System.String')");

      【讨论】:

      • 欢迎来到 Stack Overflow!在发布自己的答案之前,请考虑阅读其他人的答案。您的回答已被提及here
      猜你喜欢
      • 2010-11-13
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多