Orderby() not ordering numbers correctly c#

后端 未结 12 1713
渐次进展
渐次进展 2020-12-15 03:08

I am writing an app for my company and am currently working on the search functionality. When a user searches for an item, I want to display the highest version (which is st

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 03:45

    Why are you sorting in a lambda? Why don't you just sort in the query?

    var query = from r in items
                orderby int.Parse( r )
                select r;
    

    Now that we know you are using LINQ to SQL, you might consider making a standard SQL call on this one by doing something like:

    Select ..., Cast( TextWhichShouldBeIntCol As int ) As IntCol
    From ...
    

    Or even

    Select ..., Cast( TextWhichShouldBeIntCol As int ) As IntCol
    From ...
    Order By Cast( TextWhichShouldBeIntCol As int )
    

    That will bleed into your LINQ as an int (and if you use the second iteration, be ordered). That avoids having to go through the resultset twice in LINQ (once for querying, once for ordering).

提交回复
热议问题