views:

45

answers:

2

Does anyone know how to return an ordered list of strings with null values last? I have something like this:

using(var context = new DomainEntities())
{
    var result = context.Users.OrderBy(u => u.LastName).ThenBy(u => u.FirstName);
}

My problem though is that this query returns null values before non-null values.

Any thoughts?

+2  A: 

I don't know if there's some switch somewhere that you can flip. Otherwise, the straight forward approach would probably be something along the lines of

    using (var context = new DomainEntities())
    {
        var FirstPart = context.Users.Where(u => u.LastName != null);
        var SecondPart = context.Users.Where(u => u.LastName == null);
        var Result = FirstPart.Union(SecondPart);
    }
500 - Internal Server Error
That will produce fairly ugly SQL, I suspect.
Craig Stuntz
Define ugly :) Actually, it won't be as bad as you might think - for SQL Server 2008 at least, EF turns something like this into a single db query statement.
500 - Internal Server Error
It will be one statement, yes, just overly complicated.
Craig Stuntz
+2  A: 

I would do:

using(var context = new DomainEntities())
{
    var result = context.Users.OrderBy(u => u.LastName == null)
                              .ThenBy(u => u.LastName)
                              .ThenBy(u => u.FirstName == null);
                              .ThenBy(u => u.FirstName);
}

...which should produce reasonable SQL.

Craig Stuntz
So this does work but I'm confused as to why it works. Why would specifying LastName == null return non-null values first?
devlife
Because `false` sorts before `true`.
Craig Stuntz