开发者

How to order by column with null values last in entity framework

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

using(var context = ne开发者_如何学Pythonw 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?


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.


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


var result = context.Users.OrderBy(x => x.FirstName ?? x.LastName);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜