如何按导航排序属性(集合)

how to sort by navigation property (collection)

如果导航 属性 是集合,如何按导航 属性 字段 ( entity framework ) 排序 我想按日期和导航中的日期对员工列表进行排序 属性(集合)

如果 Trans 表示类似 NameValue 对的集合,其中一个类似于 EmployeeStartDate:

employees.OrderBy(x => x.Trans.Single(t => t.Name == "EmployeeStartDate").Date));

这只是一个示例,并假设 Trans 集合始终包含必需的匹配项。

如果 Trans 只是日期的集合,那么您需要决定使用哪个日期。例如最小或最大日期。例如,按最早日期排序:

employees.OrderBy(x => x.Trans.Min(t => t.Date));

除了@Steve Py给出的答案,你也可以先select结果,然后对你想要的字段进行排序

以下是演示:

        employees = (employees.Select(d => new Employee 
                      {
                        Name= d.Name,
                        Trans= d.Trans.OrderBy(e=>e.Date).ToList()
                      })).ToList();

型号:

public class Employee
{
    [Key]
    public string Name { get; set; }
    public ICollection<Trans> Trans{ get; set; }
}

public class Trans
{
    public int ID { get; set; }
    public DateTime Date { get; set; }
}