47

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?

4 Answers 4

91

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.

EDIT: explanation (taken from Craig's comment):

Because false sorts before true.

4
  • 7
    So this does work but I'm confused as to why it works. Why would specifying LastName == null return non-null values first?
    – devlife
    May 18, 2010 at 22:39
  • 20
    Because false sorts before true. May 19, 2010 at 1:30
  • Is that first semi-colon a type-o (after the check for u.FirstName == null) ?
    – WEFX
    Feb 14, 2012 at 17:34
  • 2
    to make this answer complete, I think it is better to add your comment to the answer itself. "Because false sorts before true." Nov 25, 2018 at 15:49
5

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);
    }
3
  • 3
    That will produce fairly ugly SQL, I suspect. May 12, 2010 at 14:26
  • 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. May 12, 2010 at 17:22
  • It will be one statement, yes, just overly complicated. May 13, 2010 at 13:08
5
var result = context.Users.OrderBy(x => x.FirstName ?? x.LastName);
1
  • EF Core 6 gives me ....could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
    – Dan Cook
    Jul 13, 2022 at 9:19
0

With mysql you can use dash symbol before the column name inside OrderBy, like so:

dbContext.Stats.OrderByDescending(i => -i.Bound).ToList();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.