2009-08-20 59 views
8

有沒有什麼辦法在LINQ做OrderBy,然後用ThenBy做一個ThenBy使用父對象的子對象進行二級排序?LINQ OrderBy名稱ThenBy ChildrenCollection.Name

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

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

BTW:當我嘗試了上面,然後做一個ToList()就可以了,我得到這個錯誤:

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

預先感謝任何幫助或指導。

回答

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); 
2

由於百貨商店是一個集合,你必須把它轉化爲一個標量使用它排序。

一種選擇是選擇集合中的單個實體,例如,第一部門的名稱:

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