在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
提前感谢您的任何帮助或指导。
答案 0 :(得分:17)
您似乎正在尝试获取按组和部门名称排序的所有部门的列表。如果是这样,那么你可能想做这样的事情:
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);
答案 1 :(得分:2)
由于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())