C# - Linq to SQL - 按嵌套 class 的元素排序列表

C# - Linq to SQL - Order a List by an element of a nested class

我在 WebApi 中使用 Linq SQL return 从数据库到前端的对象列表。

假设模型看起来像这样:

public class Course
{
    public int ID { get; set; }
    public string NAME { get; set; }       
}
public class Schedules
{
    public int id { get; set; }
    public int courseid
    public datetime start { get; set; }
} 

此外,我在一个控制器中的 Linq-to-SQL 看起来像这样:

...
...
var list =    (from xx in xx.Courses
              select new Course
              {
                  ID = xx.ID,
                  NAME = xx.NAME,
                  Schedules = (from yy in yy.Schedules
                              where xx.ID == yy.courseid
                              select new Schedules
                              {
                                 id = yy.id,
                                 courseid = yy.courseid,
                                 start = yy.start
                              }).toList()
              }).toList()
              ...
              ...

现在我需要按 Schedules.start 的最小值按升序对 "list" 进行排序。这意味着,输出应该首先给我最早开始的元素。另外没有计划的课程应该在最后给出。

最后的输出应该是这样的:

[{"ID":5, "NAME":"NAME1", "Schedules":[{"id":10, "courseid":5 , "start":"2017-12-15 00:00:00.000"}, {"id":8, "courseid":5, "start":2017-12-20 00:00:00.000"}]}],[{"ID":1, "NAME" :"NAME1", "Schedules":[{"id":9, "courseid":1, "start":2017-12-16 00:00:00.000"}, {"id":2, "courseid":1, "start":"2017-12-17 00:00:00.000"}]}]

提前致谢。

我处于这样一种情况,我需要根据子项 属性 的值对父项进行排序。

var list =    (from xx in xx.Courses
              select new Course
              {
                  ID = xx.ID,
                  NAME = xx.NAME,
                  Schedules = (from yy in yy.Schedules
                              where xx.ID == yy.courseid
                              select new Schedules
                              {
                                 id = yy.id,
                                 courseid = yy.courseid,
                                 start = yy.start
                              }).toList()
              }).OrderBy(mc => mc.Schedules.Min(dc => dc.start)).toList()