LINQ OrderBy名称ThenBy ChildrenCollection.Name

有没有什么办法在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())
链接地址: http://www.djcxy.com/p/37643.html

上一篇: LINQ OrderBy Name ThenBy ChildrenCollection.Name

下一篇: LINQ ".Include" orderby in subquery