首先按 null 排序,然后按降序排序

时间:2021-03-22 10:57:13

标签: c# .net linq entity-framework-core

我有 LINQ 脚本,其中 group by key 可能为 null。我得到了正确的结果,现在我想先按空排序,然后按降序排序。因为 group by key 可以为 null 所以我不能检查为 .hasValue!

在以下方法中,我收到 null 异常,因为我似乎没有按顺序正确处理 null?

var v25 = (from transaction in filteredTransactions
       join schedule in schedules on
       new { siteId = transaction.LoginSiteID, startDate = transaction.LoginDateTime.Date, payrollNumber = transaction.PayrollNumber } equals
       new { siteId = schedule.SiteId, startDate = schedule.StartTime.Value.Date, payrollNumber = schedule.PayrollNumber }
          into ezi_s_t
       from scheduleTransactions in ezi_s_t.DefaultIfEmpty()
       group transaction by scheduleTransactions into groupedScheduleTransactions
       select new
       {
           Schedule = groupedScheduleTransactions.Key,
           Transactions = groupedScheduleTransactions.ToList()
       }
     )
     .OrderBy(x=> x.Schedule == null? null : x.Schedule.EziScheduleId)
     .ToList();

1 个答案:

答案 0 :(得分:4)

当它为空时需要OrderByDescending(),然后使用ThenByDescending()

.OrderByDescending(x=> x.Schedule == null)
.ThenByDescending(x => x.Schedule?.EziScheduleId);

关于您的评论,您收到 System.NullReferenceException 错误的原因是因为如果 Schedule 为空,您将无法访问其属性(因为没有),因此您需要更改 {{1} }到x.Schedule.EziScheduleId

直播Demo