In entity framework, how do I sort by column with null values last?

entity-framework

Question

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?

1
29
5/11/2010 9:59:31 PM

Accepted Answer

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.

55
2/15/2012 3:55:30 AM

Popular Answer

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);
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow