Sort string elements in datatable as int using C #

I have numeric codes stored in a DataTable. When I try to sort it using a DataView, it sorts the column by row. What is the easiest way to sort data as an integer / number?

DataView view = dt.DefaultView(); view.Sort = "Code asc"; dt = view.ToTable(); 

Data in datatable: 128, 123, 112, 12, 126

after sorting shows: 112, 12, 123, 126, 128

expected result: 12, 112, 123, 126, 128

+4
source share
3 answers

Here is an example of work. You can create another DataTable via Clone and change the column data type 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"; 
+10
source

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

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

One option is to add a calculated column with the correct type and sort it.

Like this:

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

All Articles