Search code examples
c#linqentity-framework-4

How to make string appear first in order by in linq statement


How can I do the following SQL statement using Linq?

SELECT * FROM myTable
ORDER BY 
CASE myColumnName
WHEN 'Cats' THEN 1
WHEN 'Bear' THEN 2
ELSE 99
END, myColumnName

If myColumnName contains a list of animals and I want to sort by that column, but want Cats to appear first in the results then bears, is this possible to do this with a Linq statement?


Solution

  • Something like:

    var res = from p in context.myTable
              let oOrder = ( p.myColumnName == "Cats" ? 1 :
                             p.myColumnName == "Bear" ? 2 : 99)
              orderby oOrder, p.myColumnName
              select p;