how to sort varchar column containing numeric values with linq lambdas to Entity

前端 未结 2 451
长发绾君心
长发绾君心 2021-01-14 06:22

I am using linq lambdas to query the MySql (Note MySql not Sql) with Entity Framwork in MVC. Now i have one table product one of column this table is pric

相关标签:
2条回答
  • 2021-01-14 06:46

    You can simulate fixed PadLeft in LINQ to Entities with the canonical function DbFunctions.Right like this

    instead of this

    a.price.PadLeft(10, '0')
    

    use this

    DbFunctions.Right("000000000" + a.price, 10)
    

    I haven't tested it with MySql provider, but canonical functions defined in the DbFunctions are supposed to be supported by any provider.

    0 讨论(0)
  • 2021-01-14 06:52

    It looks right as sorting ascending But when i use OrderByDescending.ThenBy it gives

    106,185,400,34,59,59

    That's because you're ordering by length descending, then value ascending.
    What you need is simply to sort both by descending;

    query = query.OrderByDescending(a => a.price.Length)
                  .ThenByDescending(a => a.price);
    

    This should be faster than prepending numbers to sort, since you don't need to do multiple calculations per row but can instead sort by existing data.

    0 讨论(0)
提交回复
热议问题