Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ OrderBy Name ThenBy ChildrenCollection.Name

Is there any way in LINQ to do an OrderBy and then do a ThenBy with the ThenBy using the children of the parent object to do the secondary ordering?

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

In the above case, c.Departments is an EntityCollection.

BTW: When I try the above and then do a ToList() on it, I get this error:

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

Thanks in advance for any help or guidance.

like image 908
TehOne Avatar asked Aug 20 '09 07:08

TehOne


People also ask

What is difference between OrderBy and ThenBy in Linq?

The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

What is OrderBy in Linq?

LINQ includes following sorting operators. Sorting Operator. Description. OrderBy. Sorts the elements in the collection based on specified fields in ascending or decending order.

Is linq OrderBy stable?

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.


2 Answers

It seems like you're trying to get a list of all departments ordered by group then department name. If so, then you probably want to do something like this:

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

Or in method syntax:

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);
like image 135
dahlbyk Avatar answered Oct 20 '22 16:10

dahlbyk


Since Deparment is a collection, you have to transform it to a scalar to use it for sorting.

One option is to select a single entity to in the collection, e.g. the name of the first department:

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

Another option is to order by a property of the collection itself, e.g. the number of departments:

_repository.GetActiveDepartmentGroupsWithDepartments()
   .OrderBy(c => c.DepartmentGroupName)
   .ThenBy(c => c.Departments.Count())
like image 40
Akselsson Avatar answered Oct 20 '22 17:10

Akselsson