Sort string items in a datatable as int using c#

前端 未结 3 1491
野的像风
野的像风 2020-12-01 19:28

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/numb

相关标签:
3条回答
  • 2020-12-01 20:00

    When you are creating a column in data table, define it as typeof(int)

    dt.Columns.Add("Code", typeof(int));
    
    0 讨论(0)
  • 2020-12-01 20:03

    One option is to add a Calculated column with the right type and sort on it.

    Like this:

    dt.Columns.Add( "Int32_Code", typeof( int ), "Code" );
    dt.DefaultView.Sort("Int32_Code");
    dt = dt.DefaultView.ToTable();
    
    0 讨论(0)
  • 2020-12-01 20:16

    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";
    
    0 讨论(0)
提交回复
热议问题