Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort LINQ query by child collection's child property?

I have these objects:

public class Class
{
     public Guid Id {get;set;}
     public string Name {get;set;}
     public virtual ICollection<Schedule> Schedules{get;set;}
}

public class Schedule
{
     public Guid Id {get;set;}
     public virtual DayOfTheWeekId {get;set;}
     public virtual DayOfTheWeek {get;set;}
     public DateTime StartTime {get;set;}
     public DateTime EndTime {get;set;}
}

My current query looks like this, but I get this exception: At least one object must implement IComparable.:

    Repository
.Get(c => c.Schedules.Any(s => s.DayOfTheWeekTypeId == dayOfTheWeekId))
.OrderBy(e => e.Schedules.OrderBy(s => s.StartDateTime)).ToList()

when I set the times i always use the same day, because I need to show classes on certain days of the week. That is where the DayOfTheWeek object comes into play. This is how I am setting the times:

var schedule = new Schedule{
                           StartDateTime = new DateTime(1999,1,1) + new TimeSpan(9, 15, 0),
                           EndDateTime = new DateTime(1999,1,1) + new TimeSpan(9, 15, 0),
                           DayOfTheWeekTypeId = 1
                           }

Update:

Thinking about this, I guess I may want grouping...

like image 830
DDiVita Avatar asked Dec 05 '25 13:12

DDiVita


1 Answers

You're trying to order by a sequence. What does that even mean?

It would make more sense to order by - say - the earliest event in the schedule:

.OrderBy(e => e.Schedules.Min(s => s.StartDateTime))

I don't know whether that will work, but it at least makes more sense. (It would work in LINQ to Objects. I have no idea about EF though.)

like image 105
Jon Skeet Avatar answered Dec 08 '25 19:12

Jon Skeet