Linq2Sql cannot order anonymous type?

I have some SQL that executes a statement in order. It works fine. I cannot reproduce it as Linq2Sql.

Here's a quick hacked version of SQL I made, simplified and really disabled. Please ignore what sql (sane business logic) is trying to do as I did for the question.

SELECT      
    u.Id,
    u.Name
FROM Users u
ORDER BY CASE 
            WHEN u.Name IS NULL THEN 1
            WHEN LEN(u.Name) < 3 THEN 2
            WHEN LEN(u.Name) < 10 THEN 3
            WHEN LEN(u.Name) < 5555 THEN 4
            ELSE 5
        END ASC

      

When I try this in some Linq2Sql .. I get an anonymous error.

Here is the Linq2Sql code: _

from u in db.User
orderby new {
            UserNameType = (u.Name == null ? 1 :
                            u.Name.Length < 3 ? 2 :
                            u.Name.Length < 10 ? 3 :
                            u.Name.Length < 5555 ? 4 :
                            5)
             }
select u;

      

Any help on how can I order a case statement?

+1


source to share


1 answer


Don't create an anonymous type, just execute your condition directly on your object.



orderby (u.Name == null ? 1 :
         u.Name.Length < 3 ? 2 :
         u.Name.Length < 10 ? 3 :
         u.Name.Length < 5555 ? 4 :
         5)

      

+5


source







All Articles