3

I have a datatable (.Net) with multiple columns. One of the columns say RollNo is of string type but contains numeric data. Eg. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14. I am trying to sort using the following:

string sql = 
  "Select StudentID, RollNo, AdmissionID,(FirstName + Space(1) + Isnull(MiddleName,'') + Space(1) + Isnull(LastName,'')) as Name," +
  " PermState as State from Students where ClassId  = '" + ddlClass.SelectedValue + "'" +
  " order by RollNo";

DataTable dt = bl.GetDataSet(sql);       
dt.DefaultView.Sort = "RollNo";  

But after sorting I get the result as 1, 10, 11, 12, 13, 14, 2, 3, 4, 5, 6, 7, 8, 9.

How to solve it?

3 Answers 3

7

You can use Linq-To-DataSet and cast the string to int:

DataTable ordered = dt.AsEnumerable()
                      .OrderBy(r => int.Parse(r.Field<String>("RollNo")))
                      .CopyToDataTable();

You need to add a reference to System.Data.DataSetExtensions.dll and using System.Linq;

Note that you can omit the CopyToDataTable if you don't need it, i've showed it just to demonstrate how to get a DataTable from the IEnumerable<DataRow>.

Sign up to request clarification or add additional context in comments.

3 Comments

Fantastic! Tim, Thanks for your support. But what if RollNo field also contains alphanumeric data along with numeric?
That depends on the format. In general Regex is your friend. You can use any kind of code in Linq.
I need sample data to know how to sort that numerically. But that would be out of scope of this question anyway, because it would a a Regex question. I would ask another question "How to get a number out of this string".
1

Don't do it if your DB is large. You have to either make "string to numeric" conversion in your sql statement(that means on the DB server), which is costly, or have to read all the table to memory and make this sort there which is also costly.

I would create a new numeric field(column) and make this conversion once as a batch process.

Comments

0
        DataTable dt = GetData();
        dt.Columns.Add("RollNo1", typeof(Int32));
        foreach (DataRow item in dt.Rows)
        {
            item["RollNo1"] = item["RollNo"];
        }
        dt.DefaultView.Sort = "RollNo1";
        dt.Columns.Remove("RollNo");
        dataGridView1.DataSource = dt;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.