I have the following query:
public IEnumerable GetAllTeamsWithMembers(int ownerUserId)
{
return _ctx.Teams
.
Unfortunately eager loading (Include) doesn't support any filtering or sorting of loaded child collections.
But as stated in the accepted answer, you can sort each collection after they've been eager loaded. I wrote an extension method that handles sorting a collection by a child property easily in place so there is no need for reassignment:
public static class Extensions
{
public static void SortOn(this List enumerable, Expression> expression)
{
var type = expression.Parameters[0].Type;
var memberName = ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;
enumerable.Sort((x, y) =>
{
var first = (IComparable)type.GetProperty(memberName).GetValue(x);
var second = (IComparable)type.GetProperty(memberName).GetValue(y);
return first.CompareTo(second);
});
}
}
Then sorting the child collections could be succinctly written as:
foreach (var team in teams)
team.TeamMembers.SortOn(_ => _.Name);