tags:

views:

354

answers:

1

Hi folks,

I have some SQL that does an order by case statement. It works fine. I can't replicate it as Linq2Sql.

Here's a quick hacked up version of the SQL i made, simplified and really dumbed down. Please ignore what the sql is trying to do (business logic wise) as i made this up, 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 how i can order by a case statement?

+3  A: 

Don't construct an anonymous type, just do your conditional 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)
GalacticCowboy
cheers! thanks heaps.
Pure.Krome