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())


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因