【问题标题】:Order by null first and then in descending order首先按null排序,然后按降序排列
【发布时间】:2023-03-05 17:55:01
【问题描述】:

我有 LINQ 脚本,其中按键分组可能为空。我得到了正确的结果,现在我想先按 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();

【问题讨论】:

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


【解决方案1】:

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

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

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

直播Demo

【讨论】:

  • 建议编辑:EziScheduleId 应该用于按Ascending 顺序搜索,所以应该使用ThenBy
  • @TomasChabada 但 OP 说“然后按降序排列”,但我只是提出解决方案,一个 OP 可以决定
  • 你说得对,我被 OP 的代码弄糊涂了
  • 是的,你是对的。其实你说了之后,我看了一下代码,改了答案,然后我记得问题中提到了。
  • 我仍然收到错误 System.NullReferenceException: '对象引用未设置为对象的实例。' f__AnonymousType22j__TPar, j__TPar>.Schedule.get 返回 null。
猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 2020-02-15
  • 2013-06-29
  • 2014-01-18
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多