Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

sorting - Sort string items in a datatable as int using c#

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...