LINQ OrderBy Name ThenBy ChildrenCollection.Name

c# entity-framework linq linq-to-entities

在LINQ中有没有办法做一个OrderBy,然后用ThenBy做一个ThenBy,使用父对象的子进行二次排序?

_repository.GetActiveDepartmentGroupsWithDepartments().OrderBy(c => c.DepartmentGroupName).ThenBy(c => c.Departments.OrderBy(d => d.DepartmentName))

在上面的例子中,c.Departments是一个EntityCollection。

顺便说一句:当我尝试上面的内容然后对其执行ToList()时,我收到此错误:

DbSortClause expressions must have a type that is order comparable.
Parameter name: key

在此先感谢任何帮助或指导。

一般承认的答案

您似乎正在尝试获取按组和部门名称排序的所有部门的列表。如果是这样,那么你可能想做这样的事情:

var res = from c in _repository.GetActiveDepartmentGroupsWithDepartments()
          from d in c.Departments
          orderby c.DepartmentGroupName, d.DepartmentName
          select d;

或者在方法语法中:

var res = _repository.GetActiveDepartmentGroupsWithDepartments()
                     .SelectMany(c => c.Departments, (c,d) => new { c, d })
                     .OrderBy(x => x.c.DepartmentGroupName)
                     .ThenBy(x => x.d.DepartmentName)
                     .Select(x => x.d);

热门答案

由于Deparment是一个集合,您必须将其转换为标量以将其用于排序。

一种选择是在集合中选择单个实体,例如第一个部门的名称:

_repository.GetActiveDepartmentGroupsWithDepartments()
   .OrderBy(c => c.DepartmentGroupName)
   .ThenBy(c => c.Departments
       .OrderBy(d => d.DepartmentName)
       .FirstOrDefault()
       .DepartmentName
    )

另一种选择是通过集合本身的属性来订购,例如部门的数量:

_repository.GetActiveDepartmentGroupsWithDepartments()
   .OrderBy(c => c.DepartmentGroupName)
   .ThenBy(c => c.Departments.Count())


许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因