views:

271

answers:

1

I would like to be able to store a list of expressions to execute with IQueryable.OrderBy at a later time, something like:

List<Expression<Func<MyType, object>>> list = new List<Expression<Func<MyType, object>>>();
  list.Add(x => x.Date);
  list.Add(x => x.ID);
  IOrderedQueryable<MyType> qry = query.OrderBy(list[0]).ThenBy(list[1]);

However doing this throws an InvalidOperationException - Cannot order by type 'System.Object' because the expression is defined with object and not a specific type like Expression<Func<MyType, DateTime>> or Expression<Func<MyType, int>>

How can I store a list of expressions so that I can execute them later in a OrderBy method?

+1  A: 

Do you just need to add to this ordering? You don't need to dynamically remove stuff later on? If that's the case, it's relatively straightforward:

using System;
using System.Linq;
using System.Linq.Expressions;

class QueryOrdering<T>
{
    private Func<IQueryable<T>, IOrderedQueryable<T>> function;

    public void AddOrdering<TKey>(Expression<Func<T, TKey>> keySelector)
    {
        if (function == null)
        {
            function = source => source.OrderBy(keySelector);
        }
        else
        {
            // We need to capture the current value...
            var currentFunction = function;
            function = source => currentFunction(source).ThenBy(keySelector);
        }
    }

    public IOrderedQueryable<T> Apply(IQueryable<T> source)
    {
        if (function == null)
        {
            throw new InvalidOperationException("No ordering defined");
        }
        return function(source);
    }
}

I don't like the fact that this uses mutation... it wouldn't be too hard to write an immutable version, where AddOrdering returned a new QueryOrdering<T> with the new function.

Jon Skeet
Yes, I only need to add to the ordering so this works perfectly. Thanks. I'll look into an immutable version.
David G