Ogglas
Ogglas

Reputation: 69928

OrderBy nested property

I'm trying to use OrderBy for a nested property but I can't get it to work.

Models:

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

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

Method:

List<TPRenewalCycle> cycles = renewalCycles

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

This gives me the runtime error:

At least one object must implement IComparable.

Is this due to the nullable DateTime or CaseEvents? How can I solve this?

In T-SQL I can do this:

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

Upvotes: 3

Views: 117

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Since OrderBy expression needs to supply a value to be used as the comparison key for the entire record, you need to select the earliest due date in the list:

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

If you are looking for the earliest date, as in your SQL query, you could use SelectMany instead:

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

Upvotes: 5

Related Questions