按嵌套属性排序

3

我将尝试为嵌套属性使用OrderBy,但是我无法使其正常工作。

模型:

public class TPRenewalCycle
{
    public virtual ICollection<TPCaseEvent> CaseEvents { get; set; }
}

public class TPCaseEvent
{
    public DateTime? DueDate { get; set; }
}

方法:

List<TPRenewalCycle> cycles = renewalCycles

var nextRenewalCycle = cycles.OrderBy(cycle => cycle.CaseEvents.OrderBy(caseEvent => caseEvent.DueDate)).FirstOrDefault();

这个错误提示是:

至少一个对象必须实现 IComparable 接口。

这是由于 nullable DateTimeCaseEvents 引起的吗?我该如何解决?

在 T-SQL 中,可以这么做:

SELECT CE.DueDate
  FROM TPRenewalCycles RC
  INNER JOIN TPCaseEvents CE on (CE.BusinessSystemId = RC.BusinessSystemId and CE.CaseId = RC.CaseId and CE.Action = RC.Action and CE.Cycle = RC.Cycle)
  Order by CE.DueDate

@SamvelPetrosov 不,它不应该。 - DavidG
这是Entity Framework吗? - DavidG
你可以将你的T-SQL查询几乎原封不动地转换为LINQ查询。 - Evk
cycles.OrderBy(cycle => cycle.CaseEvents.OrderBy(...)) 的意思是你尝试按照内部 OrderBy 的结果,即 IEnumerable<> 进行排序。就像“按学生的姓氏对班级进行排序”一样。 - H H
1个回答

5

由于OrderBy表达式需要提供一个值作为整个记录的比较关键字,因此您需要选择列表中最早的到期日期:

var nextRenewalCycle = cycles
    .OrderBy(cycle => cycle.CaseEvents.Select(caseEvent => caseEvent.DueDate).Min())
    .FirstOrDefault();

如果你想要查询最早的日期,就像在你的SQL查询中一样,你可以使用SelectMany

var nextRenewalCycle = cycles
    .SelectMany(cycle => cycle.CaseEvents)
    .Select(caseEvent => caseEvent.DueDate)
    .Min();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接