3

I try to order Departments by number, but since the departement number stored as a string in database, I can't just use Order by number. I try to parse it as float but it did not work. Then I tried to parse it as Double. That does not work either. Any suggestions? The following is my code.

using (var db = new Context())
{
    var datasource = (from x in db.Departments 
                      orderby double.Parse(x.DepartmentNumber) 
                      select x).ToList();
    lvData.DataSource = datasource;
    lvData.DataBind();
}

Thanks for the answer, I did the following, but the results are not entirly correct.

 var datasource = (from x in db.Departments orderby x.DepartmentNumber select x).ToList().OrderBy(Department => float.Parse(Department.DepartmentNumber));

enter image description here

Mindan
  • 979
  • 6
  • 17
  • 37
  • I'm bit supreised that `DepartmentNmber` is not type of duoble. – Maciej Los Jun 13 '17 at 20:30
  • We can't guess what your definition of "correct" is. Do you mean you want `209.01` to appear before `222`? The sorting shown in the screenshot would seem to suggest your locale uses a comma as decimal point, then parse for that. – CodeCaster Jun 13 '17 at 21:08
  • Thanks for the comment, I just figured it out and it works now. Please read my answer further down. – Mindan Jun 13 '17 at 21:10
  • Yeah see the linked duplicates. It helps to break up a problem in smaller parts, then you'll find each of them has been asked and answered before. :) – CodeCaster Jun 13 '17 at 21:11

2 Answers2

7

One solution it would be the following:

var datasource = db.Departments 
                   .ToList()
                   .OrderBy(department => double.Parse(department.DepartmentNumber));

You fetch all the data from the database in the memory of your application (by calling ToList, which requests the immediate execution of the query.) and then you make the ordering in memory.

The reason why the query below doesn't work:

var datasource = (from x in db.Departments 
                  orderby double.Parse(x.DepartmentNumber) 
                  select x).ToList();

is the fact that double.Parse cannot be translated to an equivalent function in sql and then the whole sql query be submitted to the database for execution.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

Actually the following solved the problem and provided the required results:

 var datasource = (from x in db.Departments orderby x.DepartmentNumber select x).ToList().OrderBy(Department => Convert.ToDouble(Department.DepartmentNumber, System.Globalization.CultureInfo.InvariantCulture));

enter image description here

Mindan
  • 979
  • 6
  • 17
  • 37