LINQ顺序按与底部空值降序 [英] LINQ Order By Descending with Null Values on Bottom

查看:160
本文介绍了LINQ顺序按与底部空值降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的前pression:

  troubletickets = db.ServiceTickets.Include(T => t.Company).INCLUDE(T => t.UserProfile);
troubletickets.OrderByDescending(T => t.UserProfile = NULL t​​.UserProfile.FirstName!?ZZZ);

我要检查,如果用户配置为null,因为如果我不,我会得到一个错误。问题是,有时UserProfiles.FirstName可以为null。当它为空时,这些值将被放置在列表的顶部,当我双方升序和降序排列。例如。

  // NULL,NULL,刘德华,比尔,克里斯
// NULL,NULL,克里斯,比尔,安迪

我怎样才能改变这种前pression这样,当我通过降序排列返回这样的事情,而不是:

  //克里斯·比尔,安迪,NULL,NULL


解决方案

您几乎拥有了正确的:

  troubletickets.OrderByDescending(T =>!t.UserProfile = NULL
                                      &功放;&安培; t.UserProfile.FirstName!= NULL
                                         ? t.UserProfile.FirstName
                                         :的String.Empty);

的String.Empty 永远是最低的字符串,所以它会在最后一个结束 OrderByDescending

如果你想要的东西,既升序和降序的作品,你必须分两步进行排序:

  troubletickets.OrderByDescending(T =>!t.UserProfile = NULL
                                      &功放;&安培; t.UserProfile.FirstName!= NULL)
              .ThenByDescending(T =>!t.UserProfile = NULL //或ThenBy
                                         ? t.UserProfile.FirstName
                                         : 空值);

这工作,因为真>假

I have this expression:

troubletickets = db.ServiceTickets.Include(t => t.Company).Include(t => t.UserProfile);
troubletickets.OrderByDescending(t => t.UserProfile != null ? t.UserProfile.FirstName : "ZZZ");

I have to check if UserProfile is null because if I don't I will get an error. The problem is, sometimes UserProfiles.FirstName can be null. When it is null, those values are placed at the top of the list when I order by both ascending and descending. E.g.

// Null, Null, Andy, Bill, Chris
// Null, Null, Chris, Bill, Andy

How can I alter this expression so that when I order by descending it returns something like this instead:

// Chris, Bill, Andy, Null, Null

解决方案

You almost had it right:

troubletickets.OrderByDescending(t => t.UserProfile != null
                                      && t.UserProfile.FirstName != null
                                         ? t.UserProfile.FirstName
                                         : string.Empty);

string.Empty will always be the lowest string, so it will end up last in an OrderByDescending.

If you want something that works with both ascending and descending order, you'd have to sort in two steps:

troubletickets.OrderByDescending(t => t.UserProfile != null
                                      && t.UserProfile.FirstName != null)
              .ThenByDescending(t => t.UserProfile != null                // Or ThenBy
                                         ? t.UserProfile.FirstName
                                         : null);

This works because true > false.

这篇关于LINQ顺序按与底部空值降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆