Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I know this is old, but I was looking to accomplish the exact same thing as the OP and didn't want to use the <code>Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt;</code> in my dictionary. Mostly because I would have to implement both an <code>OrderBy</code> and <code>OrderByDescending</code> delegate.</p> <p>I ended up creating an extension method for IQueryable called <code>ObjectSort</code> which will simply check to see what the return type of the expression should be and then create a new lambda using that type so that LINQ to Entities won't freak out.</p> <p>I'm not sure if this is a good solution or not but the example below does work for <code>DateTime</code> and <code>int</code> so hopefully it can give you some ideas if you're looking to accomplish something similar!</p> <pre><code>public static IOrderedQueryable&lt;T&gt; ObjectSort&lt;T&gt;(this IQueryable&lt;T&gt; entities, Expression&lt;Func&lt;T, object&gt;&gt; expression, SortOrder order = SortOrder.Ascending) { var unaryExpression = expression.Body as UnaryExpression; if (unaryExpression != null) { var propertyExpression = (MemberExpression)unaryExpression.Operand; var parameters = expression.Parameters; if (propertyExpression.Type == typeof(DateTime)) { var newExpression = Expression.Lambda&lt;Func&lt;T, DateTime&gt;&gt;(propertyExpression, parameters); return order == SortOrder.Ascending ? entities.OrderBy(newExpression) : entities.OrderByDescending(newExpression); } if (propertyExpression.Type == typeof(int)) { var newExpression = Expression.Lambda&lt;Func&lt;T, int&gt;&gt;(propertyExpression, parameters); return order == SortOrder.Ascending ? entities.OrderBy(newExpression) : entities.OrderByDescending(newExpression); } throw new NotSupportedException("Object type resolution not implemented for this type"); } return entities.OrderBy(expression); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload