I have this two entities:
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public virtual ICollection<Class> Classes { get; set; }
}
public class Class
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; } ]
public Course Course { get; set; }
}
Now I need to list each Class grouping by Course and ordered by (descending) Course.StartDate then by Class.StartTime.
I can get to group by Course and order by Course.StartDate:
var myList = context.Classes
.GroupBy(c => c.Course)
.OrderByDescending(g => g.Key.StartDate).ToList()
But can’t manage to also order each Class by it’s StartTime. I tried this:
var myList = context.Classes
.OrderBy(c => c.StartTime)
.GroupBy(c => c.Course)
.OrderByDescending(g => g.Key.StartDate).ToList()
And even this:
var myList = context.Classes
.GroupBy(c => c.Course)
.OrderByDescending(g => g.Key.StartDate)
.ThenBy(g => g.Select(c => c.StartTime)).ToList()
But the Classes are never ordered by it’s StartTime.
*Edit for better clarification:
This is for a WebService and I must return a List<IGrouping<Course, Class>> and I really want an elegant way of doing this (i.e. using just Linq), without manually creating the list. Unless it’s not possible of course.
Any help is apreciated (I’m using EF code-first 4.3 btw).
If you need to preserve the signature, I suggest the following:
This results in a type of signature:
List<IGrouping<Course, Class>>and has them properly ordered byStartTime. This relies on the behavior ofToLookupwith respect to maintaining the order found and may be subject to change.