Order LINQ After that, by ChildrenCollection.Name.

c# entity-framework linq linq-to-entities

Question

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.

1
8
8/20/2009 7:37:00 AM

Accepted Answer

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);
17
8/20/2009 8:52:48 AM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow