title: How to create expression for ordering string by length
body: <p>I am new to expression tree.
  I need to order my collection base on string length and then string.
  I dont want to repeat my code for every entity.
  Any body know how to write it with expression tree?</p>
  
  <p>somthing like this:</p>
  
  <pre><code>public static IQueryable&lt;T&gt; OrderByPropertyOrField&lt;T&gt;(this IQueryable&lt;T&gt; queryable,
    string propertyOrFieldName, bool ascending = true)
  {
      var elementType = typeof(T);
      var orderByMethodName = ascending ? "OrderBy" : "OrderByDescending";
  
      var parameterExpression = Expression.Parameter(elementType);
      var propertyOrFieldExpression = Expression.PropertyOrField(parameterExpression, propertyOrFieldName);
      var selector = Expression.Lambda(propertyOrFieldExpression, parameterExpression);
  
      var orderByExpression = Expression.Call(typeof(Queryable), orderByMethodName,
          new[] { elementType, propertyOrFieldExpression.Type }, queryable.Expression, selector);
  
      return queryable.Provider.CreateQuery&lt;T&gt;(orderByExpression);
  }
  </code></pre>