efcore: OrderBy and ThenBy problem

I know that this came from EF6, but it is ugly construction. It is very difficult to do chain of method with conditions:

var items = db.Items;
if (condition1)
{
    items = items.OrderBy(x => x.Field1);
}
if (condition2)
{
    items = items.ThenBy(x => x.Field2); 
}

if condition1 is false, then ThenBy throw exception. There are no really need to call OrderBy first and ThenBy next. More convinient would be method AddOrderBy instead of that two. Or in addition for them.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 16 (4 by maintainers)

Most upvoted comments

@anpete @MichaelKetting reading the whole thread I tend agree that the fact that queries returned from all operators are IOrderedQueryable<T> is less than ideal. Any thoughts on this?

You can do that yourself

I tried it and this is not work. DbQuery<T> realize both IQuerable<T> and IOrderedQuerable<T>. There are no way to realize was OrderBy called or not.

Magic of OrderBy -> ThenBy work on interfaces that they return and extend (as extensition method). It work only if you call them in one chain

var items = db.Items.OrderBy(x => x.Time).ThenBy(x => x.Name)

and broke in this scenario:

var items = db.Items.AsQueryable();
items = items.OrderBy(x => x.Time);
items = items.ThenBy(x => x.Name); // oops, it is not compiled

I see what you’re saying. You can do that yourself:

static class EnumerableExtensions
{
    public static IEnumerable<T> AppendOrderBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> sortSelector)
    {
        return (source as IOrderedEnumerable<T>)?.ThenBy(sortSelector)
            ?? source.OrderBy(sortSelector);
    }
}

In general it doesn’t make a terrible amount of sense to do an AddOrderBy (meaning ThenBy) without explicitly tracking which ordering it’s coming after, since the two sorts can’t be done independently. (I’m not even sure how you got db.Items.ThenBy to compile.)

This is more of a corefx question.